blob_id stringlengths 40 40 | directory_id stringlengths 40 40 | path stringlengths 3 264 | content_id stringlengths 40 40 | detected_licenses listlengths 0 85 | license_type stringclasses 2
values | repo_name stringlengths 5 140 | snapshot_id stringlengths 40 40 | revision_id stringlengths 40 40 | branch_name stringclasses 986
values | visit_date timestamp[us] | revision_date timestamp[us] | committer_date timestamp[us] | github_id int64 3.89k 681M โ | star_events_count int64 0 209k | fork_events_count int64 0 110k | gha_license_id stringclasses 23
values | gha_event_created_at timestamp[us] | gha_created_at timestamp[us] | gha_language stringclasses 145
values | src_encoding stringclasses 34
values | language stringclasses 1
value | is_vendor bool 1
class | is_generated bool 2
classes | length_bytes int64 3 10.4M | extension stringclasses 122
values | content stringlengths 3 10.4M | authors listlengths 1 1 | author_id stringlengths 0 158 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
09192d0d832adb9572b3c902c4777c64c15aabae | 111200e4a10fd238d231d6886cddf08908da5f5c | /loops/palindrom.cpp | edf06ab0c5cf6734aa397fccdaa2a023d0c3036d | [] | no_license | pritamSarkar123/abulBariC- | 1f5b796aa2881d44561b76037253fc38b8c08642 | 00b737021855a770dd61b142a9647aa032651f35 | refs/heads/master | 2023-01-13T16:42:46.522243 | 2020-11-21T09:06:26 | 2020-11-21T09:06:26 | 272,079,444 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 248 | cpp | #include<iostream>
using namespace std;
int main(){
int num,numcp,rev=0;
cin>>num;
numcp=num;
while(num){
int r=num%10;
rev=rev*10+r;
num/=10;
}
if(numcp==rev)
cout<<"Palindrom"<<endl;
else
cout<<"Not Palindrom"<<endl;
return 0;
} | [
"pritamsarkar84208220@gmail.com"
] | pritamsarkar84208220@gmail.com |
0d37c9fc4463866a146c99cd9f68c70b09e8a950 | 1257f7896aa8403e3f2161d1e9b00b9205e93edf | /system/System/detail/ClockTimer.hpp | 11342390c8537d75e64fa618b5cf9a78dcdfb557 | [] | no_license | el-bart/system | 94d3c24e54d2b1b24fbc1738f6de992ba06bb388 | 99e03de1db0855827d39a32328bbb5cbdc580823 | refs/heads/master | 2021-01-01T18:33:43.260419 | 2014-06-01T10:49:29 | 2014-06-01T10:49:29 | 5,328,168 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,772 | hpp | /*
* ClockTimer.hpp
*
*/
#ifndef INCLUDE_SYSTEM_DETAIL_CLOCKTIMER_HPP_FILE
#define INCLUDE_SYSTEM_DETAIL_CLOCKTIMER_HPP_FILE
/* public header */
#include <ctime>
#include "System/ExceptionSyscallFailed.hpp"
namespace System
{
namespace detail
{
/** \brief generic timer template to be used with different clocks.
*
* possible clocks are:
*
* CLOCK_REALTIME
* System-wide real-time clock. Setting this clock requires appropriate
* privileges.
*
* CLOCK_MONOTONIC
* Clock that cannot be set and represents monotonic time since some
* unspecified starting point.
*
* CLOCK_MONOTONIC_RAW (since Linux 2.6.28; Linux-specific)
* Similar to CLOCK_MONOTONIC, but provides access to a raw hardware-based
* time that is not subject to NTP adjustments.
*
* CLOCK_PROCESS_CPUTIME_ID
* High-resolution per-process timer from the CPU.
*
* CLOCK_THREAD_CPUTIME_ID
* Thread-specific CPU-time clock.
*/
template<clockid_t TClock>
class ClockTimer
{
public:
/** \brief exception thrown on timer error.
*/
struct ExceptionTimerError: public ExceptionSyscallFailed
{
/** \brief create execption with given message.
* \param where place where exception has been raisen.
* \param name name of the system call that failed.
* \param msg message to represent.
*/
explicit ExceptionTimerError(const Location &where, const char *name, const char *msg):
ExceptionSyscallFailed(where, name, msg)
{
}
}; // struct ExceptionTimerError
/** \brief start timer.
*/
ClockTimer(void)
{
restart();
}
/** \brief restart timer.
*/
void restart(void)
{
if( clock_gettime(TClock, &start_)!=0 )
throw ExceptionTimerError(SYSTEM_SAVE_LOCATION, "clock_gettime", "cannot read timer");
}
/** \brief returns time elapsed since timer's start.
* \return time since start, measured in seconds (and its fractions).
*/
double elapsed(void) const
{
struct timespec now;
if( clock_gettime(TClock, &now)!=0 )
throw ExceptionTimerError(SYSTEM_SAVE_LOCATION, "clock_gettime", "cannot read timer");
const double sec =now.tv_sec -start_.tv_sec;
const double nsec=now.tv_nsec-start_.tv_nsec;
return sec+nsec/(1000*1000*1000);
}
/** \brief gets timer's resolution.
* \return minimal time that can be measured by this timer
*/
static double resolution(void)
{
struct timespec res;
if( clock_getres(TClock, &res)!=0 )
throw ExceptionTimerError(SYSTEM_SAVE_LOCATION, "clock_getres", "cannot get timer's resolution");
return res.tv_sec+static_cast<double>(res.tv_nsec)/(1000*1000*1000);
}
private:
struct timespec start_;
}; // class ClockTimer
} // namespace detail
} // namespace System
#endif
| [
"bartosz.szurgot@pwr.wroc.pl"
] | bartosz.szurgot@pwr.wroc.pl |
672a88c2acf2cf318938bef04feb93ee3ac4b2e5 | 0ae6a2d4e0102a63d80a6993f38b6d0f568d135c | /src/zmq/zmqconfig.h | d623d2be3a746887ab703081dc19d1bfece58c2b | [
"MIT"
] | permissive | BullCoin-Project/BullCoin | d1d324ed6d0efcc7c6107418a0feaa6a5ffc707b | e01c79c13d27312a64ca5943a5cbd93cfbc18482 | refs/heads/master | 2020-03-09T21:47:56.002169 | 2018-04-26T12:38:48 | 2018-04-26T12:38:48 | 129,018,839 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 573 | h | // Copyright (c) 2014 The Bitcoin Core developers
// Copyright (c) 2017 The Bull Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#ifndef BULL_ZMQ_ZMQCONFIG_H
#define BULL_ZMQ_ZMQCONFIG_H
#if defined(HAVE_CONFIG_H)
#include "config/bull-config.h"
#endif
#include <stdarg.h>
#include <string>
#if ENABLE_ZMQ
#include <zmq.h>
#endif
#include "primitives/block.h"
#include "primitives/transaction.h"
void zmqError(const char *str);
#endif // BULL_ZMQ_ZMQCONFIG_H
| [
"bullcoinproject@gmail.com"
] | bullcoinproject@gmail.com |
38f0270687d2504e60014f5e0d32bb6e1ca7e99d | 54625d36c8b9925902983fd41ac6a444d1d519a7 | /src/test/TestMakeUnique.cpp | 7b5dc786d94dac37e4fd36e35262cf0d51ddb8bc | [] | no_license | erikalds/egen | 3834eb5856778113f9bbbaf139c0f6da11e0899c | 7762071c50eca56fe92e13c1cc368219734ce583 | refs/heads/master | 2021-01-25T06:05:40.760545 | 2014-04-21T14:41:30 | 2014-04-21T14:41:30 | null | 0 | 0 | null | null | null | null | ISO-8859-15 | C++ | false | false | 2,850 | cpp | /* Source file created: 2013-05-12
logsvc - logging as a service
Copyright (C) 2013 Erik ร
ldstedt Sund
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
To contact the author, e-mail at erikalds@gmail.com or through
regular mail:
Erik ร
ldstedt Sund
Darres veg 14
NO-7540 KLรBU
NORWAY
*/
#include "egen/make_unique.h"
#include <boost/test/unit_test.hpp>
BOOST_AUTO_TEST_SUITE(testMakeUnique)
struct F
{
F() {}
~F() {}
};
class Base
{
public:
virtual ~Base() {}
Base(int, const std::string&) {}
};
BOOST_FIXTURE_TEST_CASE(call_make_unique, F)
{
std::unique_ptr<Base> a = egen::make_unique<Base>(23, "asdf");
BOOST_CHECK(a != nullptr);
}
class Derived : public Base
{
public:
Derived(const std::string& s, int i, double) : Base(i, s) {}
};
BOOST_FIXTURE_TEST_CASE(call_make_unique_on_derived_and_save_to_Base, F)
{
std::unique_ptr<Base> a = egen::make_unique<Derived>("foobar", 42, 234.5);
BOOST_CHECK(a != nullptr);
}
BOOST_AUTO_TEST_SUITE_END()
/*
The defined macros are:
BOOST_ERROR(message)
BOOST_FAIL(message)
BOOST_IS_DEFINED(symbol)
BOOST_level(condition)
BOOST_level_MESSAGE(condition, message)
BOOST_level_THROW(expression, exception_type)
BOOST_level_EXCEPTION(expression, exception_type, P)
BOOST_level_NO_THROW(expression)
BOOST_level_EQUAL(left_expression, right_expression)
BOOST_level_NE(left_expression, right_expression)
BOOST_level_LT(left_expression, right_expression)
BOOST_level_LE(left_expression, right_expression)
BOOST_level_GT(left_expression, right_expression)
BOOST_level_GE(left_expression, right_expression)
BOOST_level_CLOSE(left_expression, right_expression, percentage)
BOOST_level_CLOSE_FRACTION(left_expression, right_expression, fraction)
BOOST_level_SMALL(left_expression, right_expression, T)
BOOST_level_PREDICATE(predicate_function, arguments)
BOOST_level_EQUAL_COLLECTIONS(left_begin, left_end, right_begin, right_end)
BOOST_level_BITWISE_EQUAL(left_expression, right_expression)
Three levels of errors are defined:
Level | Errors counter | Test execution
--------+----------------+---------------
WARN | not affected | continues
CHECK | increased | continues
REQUIRE | increased | aborts
*/
| [
"erikalds@gmail.com"
] | erikalds@gmail.com |
13b0db7f9ea2f0c8364c1343a66164af6f3790dc | 3cdb62674b89360d5b03d77994e51c87045e04c3 | /FightLandlordVS/mcts_ucb.cpp | f2fc6518cf21702e612c3d9369b2908e2f352d35 | [] | no_license | ldeng-ustc/FightLandlordVS | 8ec7393c3ba708820b3e14b43df9ff565c9abb88 | 21e357b5722a2a02e211a7ce6a38d4523ed0e200 | refs/heads/master | 2020-06-06T14:24:49.911148 | 2019-06-19T15:58:52 | 2019-06-19T15:58:52 | 192,763,485 | 2 | 0 | null | null | null | null | GB18030 | C++ | false | false | 5,681 | cpp | #include "stdafx.h"
#include "mcts_ucb.h"
#include <tuple>
#include <fstream>
#include <algorithm>
const int MCTS_UCB::timeLimit = (int)(4 * CLOCKS_PER_SEC);
const double MCTS_UCB::confident = 1.96;
int tttt = 0;
MCTS_UCB::MCTS_UCB(Game game) :board(game), r(1725)
{
sumPlay = 0;
maxPlay = 0;
maxPlayWin = 0;
maxMove = -1;
secPlay = 0;
secPlayWin = 0;
secMove = -1;
winAndPlay.clear();
winAndPlay.rehash(5000000);
}
MCTS_UCB::MCTS_UCB(MCTS_Board board) :board(board), r(1725)
{
sumPlay = 0;
maxPlay = 0;
maxPlayWin = 0;
maxMove = -1;
secPlay = 0;
secPlayWin = 0;
secMove = -1;
winAndPlay.clear();
winAndPlay.rehash(5000000);
}
long long MCTS_UCB::getBestAction(int cntTimeLimit)
{
vector<long long> choices(10);
board.getActions(choices);
if (choices.size() == 1u)
return choices[0];
long long hand = board.getCntHand();
for (auto x : choices)
{
if (x == hand)
return x;
}
int st = clock();
int times = 0;
int last = st;
while ((clock() - st) < cntTimeLimit)
{
MCTS_Board tmpBoard = board;
runSimulations(tmpBoard);
if ((((maxPlayWin / (double)maxPlay) > 0.99) && maxPlay > 2000) || (maxPlay - secPlay > 800 && secMove != -1)/* || sumPlay > 10000*/) //่ฅๆไธชๅณ็ญๆจกๆๆฌกๆฐๅทฒ่ฟๅคงไบๅ
ถๅฎๅณ็ญ๏ผไนๅฏๆๅ้ๅบ
{
//cout << "break!"<<endl;
break;
}
times++;
//if ((times & 0x3ff) == 0)
//{
// cout << clock() - last << endl;
// last = clock();
//}
}
long long move = selectBestMove();
return move;
}
const unordered_map<long long, pair<int, int> >& MCTS_UCB::getResultList()
{
return winAndPlay[board];
}
void MCTS_UCB::runSimulations(MCTS_Board& board)
{
vector<tuple<MCTS_Board, long long, int> > path; //่ฎฐๅฝๅชไฝ็ฉๅฎถๅจๅชไธชๅฑ้ขไธไบๅช็งไธๆณ
bool expand = false; //ๆฌๆฌกๆจกๆๆฏๅฆๅทฒๆๅฑ
while (board.isWin() == -1) //ๆจกๆ่ณๆไบบ่ท่
{
vector<long long> choices(10);
board.getActions(choices);
unordered_map<long long, pair<int, int> > &tmpResult = winAndPlay[board];
bool flag = false; //ๆฏๅฆๆ็ๆณๆฒกๆๆจกๆ
double maxUCB = 0;
long long move = 0;
for (auto x : choices)
{
if (tmpResult.count(x) == 0)
{
flag = true;
break;
}
double cntUCB = getUCB(board, x);
if (cntUCB > maxUCB)
{
maxUCB = cntUCB;
move = x;
}
}
if (flag) //้ๆบ็ๆณ
{
move = choices[r.next(0, choices.size() - 1)];
}
//cout << "sel:" << Util::getString(move) << endl;
if (tmpResult.count(move) == 0) //ๆฒกๆ็ป่ฎกไฟกๆฏ๏ผๆฒกๆๅฑ่ฟ๏ผๅๆๅฑ
{
if (!expand)
{
expand = true;
winAndPlay[board][move] = pair<int, int>(0, 0);
path.push_back(make_tuple(board, move, board.getcntPlayer()));
}
}
else
{
path.push_back(make_tuple(board, move, board.getcntPlayer()));
}
board.play(move);
}
bool winner[NumOfPlayer] = { false };
if (board.isWin() == 0)
winner[0] = true;
else
winner[1] = winner[2] = true;
int siz = path.size();
for (int i = 0; i < siz;i++) //ๅๅไผ ๆญ
{
auto &x = path[i];
pair<int, int> &data = winAndPlay[get<0>(x)][get<1>(x)];
if (winner[get<2>(x)])
{
data.first++;
}
data.second++;
if (i == 0)
{
if (data.second > maxPlay)
{
if (get<1>(x) == maxMove)
{
maxPlay = data.second;
maxPlayWin = data.first;
}
else
{
secPlay = maxPlay;
secPlayWin = maxPlayWin;
secMove = maxMove;
maxPlay = data.second;
maxPlayWin = data.first;
maxMove = get<1>(x);
}
}
else if (data.second > secPlay)
{
if (get<1>(x) == maxMove)
;
else
{
secPlay = data.second;
secPlayWin = data.first;
secMove = get<1>(x);
}
}
}
}
sumPlay++;
}
long long MCTS_UCB::selectBestMove()
{
vector<long long> choice(10);
board.getActions(choice);
double winRate = -1.0;
long long move = 0;
for (auto x : choice)
{
pair<int, int> data = winAndPlay[board][x];
int win = data.first;
int play = data.second;
if (play != 0)
{
double cntRate = win / (double)play;
if (cntRate > winRate)
{
move = x;
winRate = cntRate;
}
//cout << Util::getString(x) << endl;
//cout << win << '/' << play << endl;
}
}
//cout << sumPlay << endl;
return move;
}
void MCTS_UCB::play(long long move)
{
auto &data = winAndPlay[board];
if (data.count(move) != 0)
sumPlay = data[move].second;
else
sumPlay = 0;
maxPlay = 0;
maxPlayWin = 0;
maxMove = -1;
secPlay = 0;
secPlayWin = 0;
secMove = -1;
board.play(move);
}
| [
"ldeng@mail.ustc.edu.cn"
] | ldeng@mail.ustc.edu.cn |
64e004ba3d00e38bfcc1c006f494c4917a26498b | 1f539a85a033ab4d027598513ecbe51375c0007b | /euler/client/status.cc | 04065d38fde78275b5763765c6893cbfbb8f54b8 | [
"BSD-3-Clause",
"Zlib",
"BSD-2-Clause-Views",
"Apache-2.0",
"BSD-2-Clause"
] | permissive | algoworker/euler | f9b95b6e9bb36558e50207e6da6c9e7c3829bfcb | 3e4b7507552a71b58251241c96959a5b55d121d3 | refs/heads/master | 2023-04-03T12:09:55.206112 | 2021-04-16T07:36:26 | 2021-04-16T07:36:26 | 296,631,078 | 0 | 0 | Apache-2.0 | 2020-09-18T13:37:08 | 2020-09-18T13:37:08 | null | UTF-8 | C++ | false | false | 828 | cc | /* Copyright 2018 Alibaba Group Holding Limited. 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.
==============================================================================*/
#include "euler/client/status.h"
namespace euler {
namespace client {
const Status& Status::OK = Status();
} // namespace client
} // namespace euler
| [
"siran.ysr@alibaba-inc.com"
] | siran.ysr@alibaba-inc.com |
416b12f468670aaf88d23d75c67581b47d2486a2 | 24ab4757b476a29439ae9f48de3e85dc5195ea4a | /lib/magma-2.2.0/src/sgeev_m.cpp | 197e71ecfbe7a30f91c130036d834193adeb61b0 | [] | no_license | caomw/cuc_double | 6025d2005a7bfde3372ebf61cbd14e93076e274e | 99db19f7cb56c0e3345a681b2c103ab8c88e491f | refs/heads/master | 2021-01-17T05:05:07.006372 | 2017-02-10T10:29:51 | 2017-02-10T10:29:51 | 83,064,594 | 10 | 2 | null | 2017-02-24T17:09:11 | 2017-02-24T17:09:11 | null | UTF-8 | C++ | false | false | 19,314 | cpp | /*
-- MAGMA (version 2.2.0) --
Univ. of Tennessee, Knoxville
Univ. of California, Berkeley
Univ. of Colorado, Denver
@date November 2016
@generated from src/dgeev_m.cpp, normal d -> s, Sun Nov 20 20:20:26 2016
@author Stan Tomov
@author Mark Gates
*/
#include "magma_internal.h"
#include "magma_timer.h"
#define REAL
/*
* Version1 - LAPACK (lapack_zgehrd and lapack_zunghr)
* Version2 - MAGMA without dT (magma_cgehrd2 and lapack_zunghr)
* Version3 - MAGMA with dT (magma_cgehrd and magma_cunghr)
* Version5 - Multi-GPU magma_cgehrd_m with T on CPU, multi-GPU magma_cunghr_m
*/
#define Version5
/*
* TREVC version 1 - LAPACK
* TREVC version 2 - new blocked LAPACK
* TREVC version 3 - blocked, single-threaded (MAGMA)
* TREVC version 4 - blocked, multi-threaded (MAGMA)
* TREVC version 5 - blocked, multi-threaded, GPU (MAGMA)
*/
#define TREVC_VERSION 4
/***************************************************************************//**
Purpose
-------
SGEEV computes for an N-by-N real nonsymmetric matrix A, the
eigenvalues and, optionally, the left and/or right eigenvectors.
The right eigenvector v(j) of A satisfies
A * v(j) = lambda(j) * v(j)
where lambda(j) is its eigenvalue.
The left eigenvector u(j) of A satisfies
u(j)**T * A = lambda(j) * u(j)**T
where u(j)**T denotes the transpose of u(j).
The computed eigenvectors are normalized to have Euclidean norm
equal to 1 and largest component real.
Arguments
---------
@param[in]
jobvl magma_vec_t
- = MagmaNoVec: left eigenvectors of A are not computed;
- = MagmaVec: left eigenvectors of are computed.
@param[in]
jobvr magma_vec_t
- = MagmaNoVec: right eigenvectors of A are not computed;
- = MagmaVec: right eigenvectors of A are computed.
@param[in]
n INTEGER
The order of the matrix A. N >= 0.
@param[in,out]
A REAL array, dimension (LDA,N)
On entry, the N-by-N matrix A.
On exit, A has been overwritten.
@param[in]
lda INTEGER
The leading dimension of the array A. LDA >= max(1,N).
@param[out]
wr REAL array, dimension (N)
@param[out]
wi REAL array, dimension (N)
WR and WI contain the real and imaginary parts,
respectively, of the computed eigenvalues. Complex
conjugate pairs of eigenvalues appear consecutively
with the eigenvalue having the positive imaginary part
first.
@param[out]
VL REAL array, dimension (LDVL,N)
If JOBVL = MagmaVec, the left eigenvectors u(j) are stored one
after another in the columns of VL, in the same order
as their eigenvalues.
If JOBVL = MagmaNoVec, VL is not referenced.
u(j) = VL(:,j), the j-th column of VL.
@param[in]
ldvl INTEGER
The leading dimension of the array VL. LDVL >= 1; if
JOBVL = MagmaVec, LDVL >= N.
@param[out]
VR REAL array, dimension (LDVR,N)
If JOBVR = MagmaVec, the right eigenvectors v(j) are stored one
after another in the columns of VR, in the same order
as their eigenvalues.
If JOBVR = MagmaNoVec, VR is not referenced.
v(j) = VR(:,j), the j-th column of VR.
@param[in]
ldvr INTEGER
The leading dimension of the array VR. LDVR >= 1; if
JOBVR = MagmaVec, LDVR >= N.
@param[out]
work (workspace) REAL array, dimension (MAX(1,LWORK))
On exit, if INFO = 0, WORK[0] returns the optimal LWORK.
@param[in]
lwork INTEGER
The dimension of the array WORK. LWORK >= (2 + nb + nb*ngpu)*N.
For optimal performance, LWORK >= (2 + 2*nb + nb*ngpu)*N.
\n
If LWORK = -1, then a workspace query is assumed; the routine
only calculates the optimal size of the WORK array, returns
this value as the first entry of the WORK array, and no error
message related to LWORK is issued by XERBLA.
@param[out]
info INTEGER
- = 0: successful exit
- < 0: if INFO = -i, the i-th argument had an illegal value.
- > 0: if INFO = i, the QR algorithm failed to compute all the
eigenvalues, and no eigenvectors have been computed;
elements and i+1:N of W contain eigenvalues which have
converged.
@ingroup magma_geev
*******************************************************************************/
extern "C" magma_int_t
magma_sgeev_m(
magma_vec_t jobvl, magma_vec_t jobvr, magma_int_t n,
float *A, magma_int_t lda,
#ifdef COMPLEX
float *w,
#else
float *wr, float *wi,
#endif
float *VL, magma_int_t ldvl,
float *VR, magma_int_t ldvr,
float *work, magma_int_t lwork,
#ifdef COMPLEX
float *rwork,
#endif
magma_int_t *info )
{
#define VL(i,j) (VL + (i) + (j)*ldvl)
#define VR(i,j) (VR + (i) + (j)*ldvr)
const magma_int_t ione = 1;
const magma_int_t izero = 0;
float d__1, d__2;
float r, cs, sn, scl;
float dum[1], eps;
float anrm, cscale, bignum, smlnum;
magma_int_t i, k, ilo, ihi;
magma_int_t ibal, ierr, itau, iwrk, nout, liwrk, nb;
magma_int_t scalea, minwrk, optwrk, lquery, wantvl, wantvr, select[1];
magma_side_t side = MagmaRight;
magma_int_t ngpu = magma_num_gpus();
magma_timer_t time_total=0, time_gehrd=0, time_unghr=0, time_hseqr=0, time_trevc=0, time_sum=0;
magma_flops_t flop_total=0, flop_gehrd=0, flop_unghr=0, flop_hseqr=0, flop_trevc=0, flop_sum=0;
timer_start( time_total );
flops_start( flop_total );
*info = 0;
lquery = (lwork == -1);
wantvl = (jobvl == MagmaVec);
wantvr = (jobvr == MagmaVec);
if (! wantvl && jobvl != MagmaNoVec) {
*info = -1;
} else if (! wantvr && jobvr != MagmaNoVec) {
*info = -2;
} else if (n < 0) {
*info = -3;
} else if (lda < max(1,n)) {
*info = -5;
} else if ( (ldvl < 1) || (wantvl && (ldvl < n))) {
*info = -9;
} else if ( (ldvr < 1) || (wantvr && (ldvr < n))) {
*info = -11;
}
/* Compute workspace */
nb = magma_get_sgehrd_nb( n );
if (*info == 0) {
minwrk = (2 + nb + nb*ngpu)*n;
optwrk = (2 + 2*nb + nb*ngpu)*n;
work[0] = magma_smake_lwork( optwrk );
if (lwork < minwrk && ! lquery) {
*info = -13;
}
}
if (*info != 0) {
magma_xerbla( __func__, -(*info) );
return *info;
}
else if (lquery) {
return *info;
}
/* Quick return if possible */
if (n == 0) {
return *info;
}
#if defined(Version3)
float *dT;
if (MAGMA_SUCCESS != magma_smalloc( &dT, nb*n )) {
*info = MAGMA_ERR_DEVICE_ALLOC;
return *info;
}
#endif
#if defined(Version5)
float *T;
if (MAGMA_SUCCESS != magma_smalloc_cpu( &T, nb*n )) {
*info = MAGMA_ERR_HOST_ALLOC;
return *info;
}
#endif
/* Get machine constants */
eps = lapackf77_slamch( "P" );
smlnum = lapackf77_slamch( "S" );
bignum = 1. / smlnum;
lapackf77_slabad( &smlnum, &bignum );
smlnum = magma_ssqrt( smlnum ) / eps;
bignum = 1. / smlnum;
/* Scale A if max element outside range [SMLNUM,BIGNUM] */
anrm = lapackf77_slange( "M", &n, &n, A, &lda, dum );
scalea = 0;
if (anrm > 0. && anrm < smlnum) {
scalea = 1;
cscale = smlnum;
} else if (anrm > bignum) {
scalea = 1;
cscale = bignum;
}
if (scalea) {
lapackf77_slascl( "G", &izero, &izero, &anrm, &cscale, &n, &n, A, &lda, &ierr );
}
/* Balance the matrix
* (Workspace: need N)
* - this space is reserved until after gebak */
ibal = 0;
lapackf77_sgebal( "B", &n, A, &lda, &ilo, &ihi, &work[ibal], &ierr );
/* Reduce to upper Hessenberg form
* (Workspace: need 3*N, prefer 2*N + N*NB + NB*NGPU)
* - added NB*NGPU needed for multi-GPU magma_sgehrd_m
* - including N reserved for gebal/gebak, unused by sgehrd */
itau = ibal + n;
iwrk = itau + n;
liwrk = lwork - iwrk;
timer_start( time_gehrd );
flops_start( flop_gehrd );
#if defined(Version1)
// Version 1 - LAPACK
lapackf77_sgehrd( &n, &ilo, &ihi, A, &lda,
&work[itau], &work[iwrk], &liwrk, &ierr );
#elif defined(Version2)
// Version 2 - LAPACK consistent HRD
magma_sgehrd2( n, ilo, ihi, A, lda,
&work[itau], &work[iwrk], liwrk, &ierr );
#elif defined(Version3)
// Version 3 - LAPACK consistent MAGMA HRD + T matrices stored,
magma_sgehrd( n, ilo, ihi, A, lda,
&work[itau], &work[iwrk], liwrk, dT, &ierr );
#elif defined(Version5)
// Version 4 - Multi-GPU, T on host
magma_sgehrd_m( n, ilo, ihi, A, lda,
&work[itau], &work[iwrk], liwrk, T, &ierr );
#endif
time_sum += timer_stop( time_gehrd );
flop_sum += flops_stop( flop_gehrd );
if (wantvl) {
/* Want left eigenvectors
* Copy Householder vectors to VL */
side = MagmaLeft;
lapackf77_slacpy( MagmaLowerStr, &n, &n, A, &lda, VL, &ldvl );
/* Generate orthogonal matrix in VL
* (Workspace: need 3*N-1, prefer 2*N + (N-1)*NB)
* - including N reserved for gebal/gebak, unused by sorghr */
timer_start( time_unghr );
flops_start( flop_unghr );
#if defined(Version1) || defined(Version2)
// Version 1 & 2 - LAPACK
lapackf77_sorghr( &n, &ilo, &ihi, VL, &ldvl, &work[itau],
&work[iwrk], &liwrk, &ierr );
#elif defined(Version3)
// Version 3 - LAPACK consistent MAGMA HRD + T matrices stored
magma_sorghr( n, ilo, ihi, VL, ldvl, &work[itau], dT, nb, &ierr );
#elif defined(Version5)
// Version 5 - Multi-GPU, T on host
magma_sorghr_m( n, ilo, ihi, VL, ldvl, &work[itau], T, nb, &ierr );
#endif
time_sum += timer_stop( time_unghr );
flop_sum += flops_stop( flop_unghr );
timer_start( time_hseqr );
flops_start( flop_hseqr );
/* Perform QR iteration, accumulating Schur vectors in VL
* (Workspace: need N+1, prefer N+HSWORK (see comments) )
* - including N reserved for gebal/gebak, unused by shseqr */
iwrk = itau;
liwrk = lwork - iwrk;
lapackf77_shseqr( "S", "V", &n, &ilo, &ihi, A, &lda, wr, wi,
VL, &ldvl, &work[iwrk], &liwrk, info );
time_sum += timer_stop( time_hseqr );
flop_sum += flops_stop( flop_hseqr );
if (wantvr) {
/* Want left and right eigenvectors
* Copy Schur vectors to VR */
side = MagmaBothSides;
lapackf77_slacpy( "F", &n, &n, VL, &ldvl, VR, &ldvr );
}
}
else if (wantvr) {
/* Want right eigenvectors
* Copy Householder vectors to VR */
side = MagmaRight;
lapackf77_slacpy( "L", &n, &n, A, &lda, VR, &ldvr );
/* Generate orthogonal matrix in VR
* (Workspace: need 3*N-1, prefer 2*N + (N-1)*NB)
* - including N reserved for gebal/gebak, unused by sorghr */
timer_start( time_unghr );
flops_start( flop_unghr );
#if defined(Version1) || defined(Version2)
// Version 1 & 2 - LAPACK
lapackf77_sorghr( &n, &ilo, &ihi, VR, &ldvr, &work[itau],
&work[iwrk], &liwrk, &ierr );
#elif defined(Version3)
// Version 3 - LAPACK consistent MAGMA HRD + T matrices stored
magma_sorghr( n, ilo, ihi, VR, ldvr, &work[itau], dT, nb, &ierr );
#elif defined(Version5)
// Version 5 - Multi-GPU, T on host
magma_sorghr_m( n, ilo, ihi, VR, ldvr, &work[itau], T, nb, &ierr );
#endif
time_sum += timer_stop( time_unghr );
flop_sum += flops_stop( flop_unghr );
/* Perform QR iteration, accumulating Schur vectors in VR
* (Workspace: need N+1, prefer N+HSWORK (see comments) )
* - including N reserved for gebal/gebak, unused by shseqr */
timer_start( time_hseqr );
flops_start( flop_hseqr );
iwrk = itau;
liwrk = lwork - iwrk;
lapackf77_shseqr( "S", "V", &n, &ilo, &ihi, A, &lda, wr, wi,
VR, &ldvr, &work[iwrk], &liwrk, info );
time_sum += timer_stop( time_hseqr );
flop_sum += flops_stop( flop_hseqr );
}
else {
/* Compute eigenvalues only
* (Workspace: need N+1, prefer N+HSWORK (see comments) )
* - including N reserved for gebal/gebak, unused by shseqr */
timer_start( time_hseqr );
flops_start( flop_hseqr );
iwrk = itau;
liwrk = lwork - iwrk;
lapackf77_shseqr( "E", "N", &n, &ilo, &ihi, A, &lda, wr, wi,
VR, &ldvr, &work[iwrk], &liwrk, info );
time_sum += timer_stop( time_hseqr );
flop_sum += flops_stop( flop_hseqr );
}
/* If INFO > 0 from SHSEQR, then quit */
if (*info > 0) {
goto CLEANUP;
}
timer_start( time_trevc );
flops_start( flop_trevc );
if (wantvl || wantvr) {
/* Compute left and/or right eigenvectors
* (Workspace: need 4*N, prefer (2 + 2*nb)*N)
* - including N reserved for gebal/gebak, unused by strevc */
liwrk = lwork - iwrk;
#if TREVC_VERSION == 1
lapackf77_strevc( lapack_side_const(side), "B", select, &n, A, &lda, VL, &ldvl,
VR, &ldvr, &n, &nout, &work[iwrk], &ierr );
#elif TREVC_VERSION == 2
lapackf77_strevc3( lapack_side_const(side), "B", select, &n, A, &lda, VL, &ldvl,
VR, &ldvr, &n, &nout, &work[iwrk], &liwrk, &ierr );
#elif TREVC_VERSION == 3
magma_strevc3( side, MagmaBacktransVec, select, n, A, lda, VL, ldvl,
VR, ldvr, n, &nout, &work[iwrk], liwrk, &ierr );
#elif TREVC_VERSION == 4
magma_strevc3_mt( side, MagmaBacktransVec, select, n, A, lda, VL, ldvl,
VR, ldvr, n, &nout, &work[iwrk], liwrk, &ierr );
#elif TREVC_VERSION == 5
magma_strevc3_mt_gpu( side, MagmaBacktransVec, select, n, A, lda, VL, ldvl,
VR, ldvr, n, &nout, &work[iwrk], liwrk, &ierr );
#else
#error Unknown TREVC_VERSION
#endif
}
time_sum += timer_stop( time_trevc );
flop_sum += flops_stop( flop_trevc );
if (wantvl) {
/* Undo balancing of left eigenvectors
* (Workspace: need N) */
lapackf77_sgebak( "B", "L", &n, &ilo, &ihi, &work[ibal], &n,
VL, &ldvl, &ierr );
/* Normalize left eigenvectors and make largest component real */
for (i = 0; i < n; ++i) {
if ( wi[i] == 0. ) {
scl = 1. / magma_cblas_snrm2( n, VL(0,i), 1 );
blasf77_sscal( &n, &scl, VL(0,i), &ione );
}
else if ( wi[i] > 0. ) {
d__1 = magma_cblas_snrm2( n, VL(0,i), 1 );
d__2 = magma_cblas_snrm2( n, VL(0,i+1), 1 );
scl = 1. / lapackf77_slapy2( &d__1, &d__2 );
blasf77_sscal( &n, &scl, VL(0,i), &ione );
blasf77_sscal( &n, &scl, VL(0,i+1), &ione );
for (k = 0; k < n; ++k) {
/* Computing 2nd power */
d__1 = *VL(k,i);
d__2 = *VL(k,i+1);
work[iwrk + k] = d__1*d__1 + d__2*d__2;
}
k = blasf77_isamax( &n, &work[iwrk], &ione ) - 1; // subtract 1; k is 0-based
lapackf77_slartg( VL(k,i), VL(k,i+1), &cs, &sn, &r );
blasf77_srot( &n, VL(0,i), &ione, VL(0,i+1), &ione, &cs, &sn );
*VL(k,i+1) = 0.;
}
}
}
if (wantvr) {
/* Undo balancing of right eigenvectors
* (Workspace: need N) */
lapackf77_sgebak( "B", "R", &n, &ilo, &ihi, &work[ibal], &n,
VR, &ldvr, &ierr );
/* Normalize right eigenvectors and make largest component real */
for (i = 0; i < n; ++i) {
if ( wi[i] == 0. ) {
scl = 1. / magma_cblas_snrm2( n, VR(0,i), 1 );
blasf77_sscal( &n, &scl, VR(0,i), &ione );
}
else if ( wi[i] > 0. ) {
d__1 = magma_cblas_snrm2( n, VR(0,i), 1 );
d__2 = magma_cblas_snrm2( n, VR(0,i+1), 1 );
scl = 1. / lapackf77_slapy2( &d__1, &d__2 );
blasf77_sscal( &n, &scl, VR(0,i), &ione );
blasf77_sscal( &n, &scl, VR(0,i+1), &ione );
for (k = 0; k < n; ++k) {
/* Computing 2nd power */
d__1 = *VR(k,i);
d__2 = *VR(k,i+1);
work[iwrk + k] = d__1*d__1 + d__2*d__2;
}
k = blasf77_isamax( &n, &work[iwrk], &ione ) - 1; // subtract 1; k is 0-based
lapackf77_slartg( VR(k,i), VR(k,i+1), &cs, &sn, &r );
blasf77_srot( &n, VR(0,i), &ione, VR(0,i+1), &ione, &cs, &sn );
*VR(k,i+1) = 0.;
}
}
}
CLEANUP:
/* Undo scaling if necessary */
if (scalea) {
// converged eigenvalues, stored in wr[i+1:n] and wi[i+1:n] for i = INFO
magma_int_t nval = n - (*info);
magma_int_t ld = max( nval, 1 );
lapackf77_slascl( "G", &izero, &izero, &cscale, &anrm, &nval, &ione, wr + (*info), &ld, &ierr );
lapackf77_slascl( "G", &izero, &izero, &cscale, &anrm, &nval, &ione, wi + (*info), &ld, &ierr );
if (*info > 0) {
// first ilo columns were already upper triangular,
// so the corresponding eigenvalues are also valid.
nval = ilo - 1;
lapackf77_slascl( "G", &izero, &izero, &cscale, &anrm, &nval, &ione, wr, &n, &ierr );
lapackf77_slascl( "G", &izero, &izero, &cscale, &anrm, &nval, &ione, wi, &n, &ierr );
}
}
#if defined(Version3)
magma_free( dT );
#endif
#if defined(Version5)
magma_free_cpu( T );
#endif
timer_stop( time_total );
flops_stop( flop_total );
timer_printf( "sgeev times n %5lld, gehrd %7.3f, unghr %7.3f, hseqr %7.3f, trevc %7.3f, total %7.3f, sum %7.3f\n",
(long long) n, time_gehrd, time_unghr, time_hseqr, time_trevc, time_total, time_sum );
timer_printf( "sgeev flops n %5lld, gehrd %7lld, unghr %7lld, hseqr %7lld, trevc %7lld, total %7lld, sum %7lld\n",
(long long) n, flop_gehrd, flop_unghr, flop_hseqr, flop_trevc, flop_total, flop_sum );
work[0] = magma_smake_lwork( optwrk );
return *info;
} /* magma_sgeev */
| [
"policmic@fel.cvut.cz"
] | policmic@fel.cvut.cz |
0f4e1fc15cd6fa46b1204eb484bdf7c10b6d8a79 | 5828584abf43a752a16d3b212a97b1e8ad0aeda8 | /muduo/net/http/HttpResponse.h | f457fb4c757de2b75305341f49ee255a474a4aa3 | [] | no_license | sofartogo/muduo-re | 50557a19fbb3fbfd00c4b9c265a390cbf0dfc23e | 97de917c15dcfb67e3b19397b365fd17a799618d | refs/heads/master | 2021-01-23T13:31:24.864271 | 2013-03-09T14:48:36 | 2013-03-09T14:48:36 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,748 | h | /*
* =============================================================================
*
* Filename: HttpResponse.h
*
* Description:
*
* Version: 1.0
* Created: 11/14/2012 11:24:20 AM
* Revision: r1
* Compiler: gcc (Ubuntu/Linaro 4.4.4-14ubuntu5) 4.4.5
*
* Author: Wang Wei (sofartogo), wangwei881116@gmail.com
* Company: ICT ( Institute Of Computing Technology, CAS )
*
* =============================================================================
*/
#ifndef MUDUO_NET_HTTP_HTTPRESPONSE_H
#define MUDUO_NET_HTTP_HTTPRESPONSE_H
#include <muduo/base/copyable.h>
#include <muduo/base/Types.h>
#include <map>
namespace muduo
{
namespace net
{
class Buffer;
class HttpResponse : public muduo::copyable
{
public :
enum HttpStatusCode
{
kUnKnown,
k200Ok = 200,
k301MovedPermanently = 301,
k400BadRequest = 400,
k404NotFound = 404,
};
explicit HttpResponse(bool close)
: statusCode_(kUnKnown),
closeConnection_(close)
{}
void setStatusCode(HttpStatusCode code)
{ statusCode_ = code; }
void setStatusMessage(const string& message)
{ statusMessage_ = message; }
void setCloseConnection(bool on)
{ closeConnection_ = on; }
bool closeConnection() const
{ return closeConnection_; }
void setContentType(const string& contentType)
{ addHeader("Content-Type", contentType); }
void addHeader(const string& key, const string& value)
{ headers_[key] = value; }
void setBody(const string& body)
{ body_ = body; }
void appendToBuffer(Buffer* output) const;
private :
std::map<string, string> headers_;
HttpStatusCode statusCode_;
string statusMessage_;
bool closeConnection_;
string body_;
};
}
}
#endif
| [
"wangwei881116@gmail.com"
] | wangwei881116@gmail.com |
fb0c87899fb7b1126d6f1158539d6ecdb6d7cde3 | 0586f62300ddb100902aced7bc999f7e80e1a4af | /Gnss_Tool/CorePlatform/CorePlatform_test/testplatform.h | 821b984157172e9a547850e0dc41af9181b21c3a | [] | no_license | FatherOctber/University-Gnss_Tool | f6a122f7fceb54ab9efea8905660608b7c9f006f | f3b2faf5f399bf99124ab64dc9ecbef368adcc63 | refs/heads/master | 2021-06-14T05:06:51.355300 | 2016-11-26T13:30:42 | 2016-11-26T13:30:42 | 72,351,349 | 0 | 2 | null | 2017-03-27T10:02:22 | 2016-10-30T13:33:01 | C++ | UTF-8 | C++ | false | false | 1,721 | h | #ifndef TESTPLATFORM_H
#define TESTPLATFORM_H
#include "coreplatform.h"
#include "QString"
using namespace PlatformModule;
#define PEN ModuleDescriptor("Pen")
#define PINEAPPLE ModuleDescriptor("Pineapple")
class AbstractTestModule: public AbstractModule
{
Q_OBJECT
protected:
QString testDataResult;
public:
AbstractTestModule(QObject *parent = 0);
QString getTestDataResult();
};
/**
* @brief The TestModule1 class
*/
class TestModule1: public AbstractTestModule
{
Q_OBJECT
public:
TestModule1(QObject *parent = 0);
virtual ModuleDescriptor getDescriptor();
virtual bool setup(AbstractPlatformBuilder *configurator);
virtual ExecResult execute(QByteArray data);
virtual ExecResult execute();
signals:
void todo();
private:
AbstractModule* penModule;
static ModuleDescriptor descriptor;
};
/**
* @brief The TestModule2 class
*/
class TestModule2: public AbstractTestModule
{
Q_OBJECT
public:
TestModule2(QObject *parent = 0);
virtual ModuleDescriptor getDescriptor();
virtual bool setup(AbstractPlatformBuilder *configurator);
virtual ExecResult execute(QByteArray data);
virtual ExecResult execute();
signals:
void voice(QByteArray data);
private:
AbstractModule* pineapleModule;
static ModuleDescriptor descriptor;
};
class TestPlatform: public CorePlatform
{
Q_OBJECT
public:
TestPlatform(QObject* parent, std::list<AbstractTestModule*> testModules);
private:
std::list<AbstractTestModule*> moduleList;
protected:
virtual void buildPlatform();
virtual bool setup(AbstractPlatformBuilder *configurator);
virtual ModuleDescriptor getDescriptor();
};
#endif // TESTPLATFORM_H
| [
"nmishnev@nmishnev-l.spb.openwaygroup.com"
] | nmishnev@nmishnev-l.spb.openwaygroup.com |
d1366151c454bd46b102ea41e624e695c526b32a | 91187640b868290f72f3eaec3d841514960298c7 | /test/eastConst.cpp | 03c2b7483fb4e5d672bcbe5f6ad3e2b21980dfe1 | [] | no_license | dmpapazog/Cpp | fd0567a4e8c53d886603abd4ea6798c54b9a2338 | 2f028cbfa40b91ad9d73e3883a6f20a7bbdf60db | refs/heads/master | 2020-04-27T17:20:32.864667 | 2019-06-27T07:41:58 | 2019-06-27T07:41:58 | 174,514,269 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 315 | cpp | #include <iostream>
#include <cstdlib>
using namespace std;
using IntPtr = int*;
int main()
{
int a = 5;
int b = 10;
IntPtr const myPtr1 = &a;
const IntPtr const myPtr2 = &b;
*myPtr1 = 4;
*myPtr2 = 9;
cout << *myPtr1 << '\n'
<< *myPtr2 << '\n';
return EXIT_SUCCESS;
} | [
"dmpapazog@gmail.com"
] | dmpapazog@gmail.com |
7027bb9e93d6506c516c39d33d42e116c58413cb | 91a29715dd26f671dd91904618c5a435baa29d67 | /Light_node.ino | 4bfd9ce3590cdf77f37e6cccf4070adf24057344 | [] | no_license | sourabhsardesai/wireless-sensor-network-esp8266- | 9a5f29bbc86b51737bdab74ab8d421f53304d25a | 675d3f48ed8eebb4e0dda259b4740e3117aa1de1 | refs/heads/master | 2020-04-19T14:07:10.931421 | 2019-01-29T21:54:42 | 2019-01-29T21:54:42 | 168,234,320 | 6 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,617 | ino |
#include <ESP8266WiFi.h> // wifi library to access the wifi apis for esp
#include <PubSubClient.h> // mqtt client library
const char* ssid = "DesiBoys"; // ssid for wifi netwrok
const char* password = "indopakdesiboys";
byte mqtt_server[] = {35, 166, 15, 82}; // my mqtt broker ip addresss, 1883 is a default port for broker
WiFiClient espClient; // declaring wifi client
PubSubClient client(espClient); // passing the wifii client for the pubsub client
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Global vraibles
char buf[30];
char* outTopic1 = "123/light";
char* inTopic1 = "123/L1";
char* clientId = "arduino1";
char* payloadOn1 = "true";
char* payloadOn2 = "false";
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Setup
// This is the function which executes to accomplish the wifi connection
void setup_wifi() {
delay(10);
// We start by connecting to a WiFi network
Serial.println();
Serial.print("Connecting to ");
Serial.println(ssid);
WiFi.begin(ssid,password); // initialise the wifi network
while (WiFi.status() != WL_CONNECTED) { // this loops till the esp connects to the internet
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("WiFi connected");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
Serial.println(WiFi.macAddress());
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void callback(char* topic, byte* payload, unsigned int length) { // this function is callback function which receives the data from the mqtt server, it is event based.
char* json;
json = (char*) malloc(length + 1); // json receives the data from the payload byte varaible
memcpy(json, payload, length); // memory has to be allocated hence memcpy functions is used to allocated dedicated memory to staore the data from payload varaible
json[length] = '\0';
Serial.println(topic);
Serial.println(json);
if (String(payloadOn2) == String(json)) // The payloadOn2 varaible is used store the expected value coming from the received and json has the current value of the data received which is compared and if the data matches the respective command is executed.
{
digitalWrite(2, HIGH);
digitalWrite(D2, HIGH); // In this case the relay is turned on
}
if (String(payloadOn1) == String(json)) // The payloadOn1 varaible is used store the expected value coming from the received and json has the current value of the data received which is compared and if the data matches the respective command is executed.
{
digitalWrite(2, LOW);
digitalWrite(D2, LOW); // In this case the relay is turned off
}
free(json);
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Reconnect function is used to keep esp connected with the server
void reconnect() {
// Loop until we're reconnected
while (!client.connected()) { // this loop makes sure that the connections is alive to the broker
Serial.print("Attempting MQTT connection...");
// Attempt to connect
if (client.connect("ESP8266Client")) { // this loop connects it with mqtt broker
Serial.println("connected");
// Once connected, publish an announcement...
client.publish("outTopic", "hello world");
client.subscribe(inTopic1); // subscribes to the topic in the inTopic1 varaible
} else {
Serial.print("failed, rc=");
Serial.print(client.state());
Serial.println(" try again in 5 seconds");
// Wait 5 seconds before retrying
delay(5000);
}
}
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// This function i executed at the begining and only once all the basic setup is stated in this function
void setup() {
int sensorPin = A0;
Serial.begin(115200);
setup_wifi(); // Make connection to the wifi
client.setServer(mqtt_server, 1883); // pass mqtt broker ip address and port number
client.setCallback(callback); // set callback function by passing callback function
Serial.println("start");
pinMode(sensorPin, INPUT); // configure the A0 pin as input
pinMode(2, OUTPUT); // configure the led pin as output
pinMode(D2, OUTPUT); // configure the D2 pin as output
// pinMode(9, INPUT); //
digitalWrite(2, HIGH); // turn the led pin high
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// This loop keeps going continuosly in which main logic is written
void loop() {
if (!client.connected()) { // checks for the continuos connection
reconnect();
}
//Serial.println("in loop");
char buf[30];
int sen1, sen2;
sen1 = analogRead(A0); // Reads the analog data from A0
float val = float(sen1) / float(1024); // Divides raw value with 1024 (3v) maximum
Serial.println ( val);
float lit_percen = float(val) * float(100); // multiplies the result with 100 to get percentage
int lit = int(lit_percen);
Serial.println ( lit);
String k = String(lit); // casting the result in string
k.toCharArray(buf, 6); // convert in the char array
client.publish(outTopic1, buf); // publish data to outopic1 varaible
Serial.println (sen1);
Serial.println ("divide ");
client.loop();
delay(2000);
}
| [
"noreply@github.com"
] | sourabhsardesai.noreply@github.com |
7ab6c1e1c3ca9526a45e0707ca589e72675620f6 | d294832cf0fba6079c46d63c61f3c4abe0d4f6ec | /sdl2/MacOSX/np2sdl2/misc/tty.cpp | f21ff1de9e4eb67126471088f9d92b0210e5af6d | [
"MIT",
"GPL-1.0-or-later"
] | permissive | meepingsnesroms/NP2kai | c48cf41d49e2a83afd217b436798f89be672275a | c7b96d0cb86685a688ee24d8f7c3cc962cfd6dd9 | refs/heads/master | 2020-12-19T10:26:58.458051 | 2020-01-23T02:10:58 | 2020-01-23T02:10:58 | 235,706,990 | 2 | 0 | MIT | 2020-01-23T02:06:51 | 2020-01-23T02:06:50 | null | UTF-8 | C++ | false | false | 6,270 | cpp | /**
* @file tty.cpp
* @brief ใทใชใขใซ้ไฟกใฏใฉในใฎๅไฝใฎๅฎ็พฉใ่กใใพใ
*/
#include "compiler.h"
#include "tty.h"
#include <errno.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/ioctl.h>
#include <IOKit/serial/ioss.h>
/**
* ใณใณในใใฉใฏใฟ
*/
CTty::CTty()
: m_fd(-1)
{
}
/**
* ใในใใฉใฏใฟ
*/
CTty::~CTty()
{
Close();
}
/**
* ใชใผใใณใใ
* @param[in] bsdPath ใใใคใน
* @param[in] speed ใใผใฌใผใ
* @param[in] param ใใฉใกใฟ
* @retval true ๆๅ
* @retval false ๅคฑๆ
*/
bool CTty::Open(const char* bsdPath, unsigned int speed, const char* param)
{
Close();
// Open the serial port read/write, with no controlling terminal, and don't wait for a connection.
// The O_NONBLOCK flag also causes subsequent I/O on the device to be non-blocking.
int fd = ::open(bsdPath, O_RDWR | O_NOCTTY | O_NONBLOCK);
if (fd < 0)
{
return false;
}
do
{
// Note that open() follows POSIX semantics: multiple open() calls to the same file will succeed
// unless the TIOCEXCL ioctl is issued. This will prevent additional opens except by root-owned processes.
if (::ioctl(fd, TIOCEXCL) == -1)
{
printf("Error setting TIOCEXCL on %s - %s(%d).\n", bsdPath, strerror(errno), errno);
break;
}
// Now that the device is open, clear the O_NONBLOCK flag so subsequent I/O will block.
if (::fcntl(fd, F_SETFL, 0) == -1)
{
printf("Error clearing O_NONBLOCK %s - %s(%d).\n", bsdPath, strerror(errno), errno);
break;
}
// Get the current options and save them so we can restore the default settings later.
struct termios options;
if (::tcgetattr(fd, &options) == -1)
{
printf("Error getting tty attributes %s - %s(%d).\n", bsdPath, strerror(errno), errno);
break;
}
// Print the current input and output baud rates.
printf("Current input baud rate is %d\n", (int) cfgetispeed(&options));
printf("Current output baud rate is %d\n", (int) cfgetospeed(&options));
tcflush(fd, TCIFLUSH);
// Set raw input (non-canonical) mode, with reads blocking until either a single character
// has been received or a one second timeout expires.
cfmakeraw(&options);
options.c_cc[VMIN] = 0;
options.c_cc[VTIME] = 10;
options.c_cflag |= (CLOCAL | CREAD);
options.c_cflag &= ~PARENB;
options.c_cflag &= ~CSTOPB;
options.c_cflag &= ~CSIZE;
options.c_cflag |= CS8;
options.c_lflag &= ~(ICANON | ECHO | ECHOE | ISIG);
options.c_iflag &= ~(IXON | IXOFF | IXANY);
options.c_oflag &= ~OPOST;
// The baud rate, word length, and handshake options can be set as follows:
cfsetspeed(&options, B19200); // Set 19200 baud
if (!SetParam(param, &options.c_cflag))
{
break;
}
// Print the new input and output baud rates. Note that the IOSSIOSPEED ioctl interacts with the serial driver
// directly bypassing the termios struct. This means that the following two calls will not be able to read
// the current baud rate if the IOSSIOSPEED ioctl was used but will instead return the speed set by the last call
// to cfsetspeed.
printf("Input baud rate changed to %d\n", (int) cfgetispeed(&options));
printf("Output baud rate changed to %d\n", (int) cfgetospeed(&options));
// Cause the new options to take effect immediately.
if (::tcsetattr(fd, TCSANOW, &options) == -1)
{
printf("Error setting tty attributes %s - %s(%d).\n", bsdPath, strerror(errno), errno);
break;
}
// The IOSSIOSPEED ioctl can be used to set arbitrary baud rates
// other than those specified by POSIX. The driver for the underlying serial hardware
// ultimately determines which baud rates can be used. This ioctl sets both the input
// and output speed.
speed_t setSpeed = speed;
if (::ioctl(fd, IOSSIOSPEED, &setSpeed) == -1)
{
printf("Error calling ioctl(..., IOSSIOSPEED, ...) %s - %s(%d).\n", bsdPath, strerror(errno), errno);
break;
}
printf("speed=%d\n", speed);
m_fd = fd;
return true;
} while (0 /*CONSTCOND*/);
::close(fd);
return false;
}
/**
* ใฏใญใผใบใใ
*/
void CTty::Close()
{
if (m_fd >= 0)
{
::close(m_fd);
m_fd = -1;
}
}
/**
* ใใผใฟๅไฟก
* @param[in] data_ptr ๅไฟกใใผใฟใฎใใคใณใฟ
* @param[in] data_size ๅไฟกใใผใฟใฎใตใคใบ
* @return ้ไฟกใตใคใบ
*/
ssize_t CTty::Read(void* data_ptr, ssize_t data_size)
{
if (m_fd < 0)
{
return 0;
}
if ((data_ptr == NULL) || (data_size <= 0))
{
return 0;
}
return ::read(m_fd, data_ptr, data_size);
}
/**
* ใใผใฟ้ไฟก
* @param[in] data_ptr ้ไฟกใใผใฟใฎใใคใณใฟ
* @param[in] data_size ้ไฟกใใผใฟใฎใตใคใบ
* @return ้ไฟกใตใคใบ
*/
ssize_t CTty::Write(const void* data_ptr, ssize_t data_size)
{
if (m_fd < 0)
{
return 0;
}
if ((data_ptr == NULL) || (data_size <= 0))
{
return 0;
}
return ::write(m_fd, data_ptr, data_size);
}
/**
* ใใฉใกใผใฟ่จญๅฎ
* @param[in] param ใใฉใกใฟ
* @param[out] cflag_ptr ใใฉใฐ
* @retval true ๆๅ
* @retval false ๅคฑๆ
*/
bool CTty::SetParam(const char* param, tcflag_t* cflag_ptr)
{
tcflag_t cflag = 0;
if (cflag_ptr != NULL)
{
cflag = *cflag_ptr;
}
if (param != NULL)
{
cflag &= ~CSIZE;
switch (param[0])
{
case '5':
cflag |= CS5;
break;
case '6':
cflag |= CS6;
break;
case '7':
cflag |= CS7;
break;
case '8':
cflag |= CS8;
break;
case '4':
default:
return false;
}
switch (param[1])
{
case 'N': // for no parity
cflag &= ~(PARENB | PARODD);
break;
case 'E': // for even parity
cflag |= PARENB;
break;
case 'O': // for odd parity
cflag |= PARENB | PARODD;
break;
case 'M': // for mark parity
case 'S': // for for space parity
default:
return false;
}
if (::strcmp(param + 2, "1") == 0)
{
cflag &= ~CSTOPB;
}
else if (::strcmp(param + 2, "2") == 0)
{
cflag |= CSTOPB;
}
else
{
return false;
}
}
if (cflag_ptr != NULL)
{
*cflag_ptr = cflag;
}
return true;
}
| [
"sylph23k@gmail.com"
] | sylph23k@gmail.com |
1a7fbba4470b878f18f5f2e1ed7667b10af0e5eb | 6ced41da926682548df646099662e79d7a6022c5 | /aws-cpp-sdk-redshift-serverless/include/aws/redshift-serverless/model/DeleteEndpointAccessResult.h | fe55a21eae644203d1a14d15956d91620f275b6d | [
"Apache-2.0",
"MIT",
"JSON"
] | permissive | irods/aws-sdk-cpp | 139104843de529f615defa4f6b8e20bc95a6be05 | 2c7fb1a048c96713a28b730e1f48096bd231e932 | refs/heads/main | 2023-07-25T12:12:04.363757 | 2022-08-26T15:33:31 | 2022-08-26T15:33:31 | 141,315,346 | 0 | 1 | Apache-2.0 | 2022-08-26T17:45:09 | 2018-07-17T16:24:06 | C++ | UTF-8 | C++ | false | false | 1,723 | h | ๏ปฟ/**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
#pragma once
#include <aws/redshift-serverless/RedshiftServerless_EXPORTS.h>
#include <aws/redshift-serverless/model/EndpointAccess.h>
#include <utility>
namespace Aws
{
template<typename RESULT_TYPE>
class AmazonWebServiceResult;
namespace Utils
{
namespace Json
{
class JsonValue;
} // namespace Json
} // namespace Utils
namespace RedshiftServerless
{
namespace Model
{
class AWS_REDSHIFTSERVERLESS_API DeleteEndpointAccessResult
{
public:
DeleteEndpointAccessResult();
DeleteEndpointAccessResult(const Aws::AmazonWebServiceResult<Aws::Utils::Json::JsonValue>& result);
DeleteEndpointAccessResult& operator=(const Aws::AmazonWebServiceResult<Aws::Utils::Json::JsonValue>& result);
/**
* <p>The deleted VPC endpoint.</p>
*/
inline const EndpointAccess& GetEndpoint() const{ return m_endpoint; }
/**
* <p>The deleted VPC endpoint.</p>
*/
inline void SetEndpoint(const EndpointAccess& value) { m_endpoint = value; }
/**
* <p>The deleted VPC endpoint.</p>
*/
inline void SetEndpoint(EndpointAccess&& value) { m_endpoint = std::move(value); }
/**
* <p>The deleted VPC endpoint.</p>
*/
inline DeleteEndpointAccessResult& WithEndpoint(const EndpointAccess& value) { SetEndpoint(value); return *this;}
/**
* <p>The deleted VPC endpoint.</p>
*/
inline DeleteEndpointAccessResult& WithEndpoint(EndpointAccess&& value) { SetEndpoint(std::move(value)); return *this;}
private:
EndpointAccess m_endpoint;
};
} // namespace Model
} // namespace RedshiftServerless
} // namespace Aws
| [
"aws-sdk-cpp-automation@github.com"
] | aws-sdk-cpp-automation@github.com |
a1f621beb7d28e64a3d55b3eca7620ba586b1102 | 8ee5416ec56b9cc1d9ad2ce48cf690fa012c5ce4 | /PhysX.Net-3/Source/ParticleFluid.cpp | 4ad58733d9ee1a2dc10a3906a1421f92298ab9b1 | [] | no_license | HalcyonGrid/PhysX.net | a573e0ceb9153c3777e71cb9d1434c5d74589df6 | 2a4bfc7a6619091bb3be20cb058f65306e4d8bac | refs/heads/master | 2020-03-26T12:30:31.701484 | 2015-09-10T04:24:00 | 2015-09-10T04:24:00 | 144,896,344 | 3 | 2 | null | 2018-08-15T19:44:31 | 2018-08-15T19:44:30 | null | UTF-8 | C++ | false | false | 1,231 | cpp | #include "StdAfx.h"
#include "ParticleFluid.h"
#include "ParticleFluidReadData.h"
ParticleFluid::ParticleFluid(PxParticleFluid* particleFluid, PhysX::Physics^ owner)
: ParticleBase(particleFluid, owner)
{
}
ParticleFluidReadData^ ParticleFluid::LockParticleFluidReadData()
{
return gcnew ParticleFluidReadData(this->UnmanagedPointer->lockParticleFluidReadData());
}
float ParticleFluid::Stiffness::get()
{
return this->UnmanagedPointer->getStiffness();
}
void ParticleFluid::Stiffness::set(float value)
{
this->UnmanagedPointer->setStiffness(value);
}
float ParticleFluid::Viscosity::get()
{
return this->UnmanagedPointer->getViscosity();
}
void ParticleFluid::Viscosity::set(float value)
{
this->UnmanagedPointer->setViscosity(value);
}
float ParticleFluid::RestParticleDistance::get()
{
return this->UnmanagedPointer->getRestParticleDistance();
}
void ParticleFluid::RestParticleDistance::set(float value)
{
this->UnmanagedPointer->setRestParticleDistance(value);
}
String^ ParticleFluid::ConcreteTypeName::get()
{
return Util::ToManagedString(this->UnmanagedPointer->getConcreteTypeName());
}
PxParticleFluid* ParticleFluid::UnmanagedPointer::get()
{
return (PxParticleFluid*)ParticleBase::UnmanagedPointer;
} | [
"david.daeschler@gmail.com"
] | david.daeschler@gmail.com |
ab21bc13c90d053ffeff60e51d390f799ddd49ac | 0eff74b05b60098333ad66cf801bdd93becc9ea4 | /second/download/squid/gumtree/squid_repos_function_192_squid-3.1.23.cpp | e44ac66e7658daa41c97872e0b84581fe5a39564 | [] | no_license | niuxu18/logTracker-old | 97543445ea7e414ed40bdc681239365d33418975 | f2b060f13a0295387fe02187543db124916eb446 | refs/heads/master | 2021-09-13T21:39:37.686481 | 2017-12-11T03:36:34 | 2017-12-11T03:36:34 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 523 | cpp | char *
fetch_credentials(ntlm_authenticate * auth, int auth_length)
{
char *p = credentials;
lstring tmp;
tmp = ntlm_fetch_string((char *) auth, auth_length, &auth->domain);
*p = '\0';
if (tmp.str == NULL)
return NULL;
memcpy(p, tmp.str, tmp.l);
p += tmp.l;
*p++ = '\\';
*p = '\0';
tmp = ntlm_fetch_string((char *) auth, auth_length, &auth->user);
if (tmp.str == NULL)
return NULL;
memcpy(p, tmp.str, tmp.l);
*(p + tmp.l) = '\0';
return credentials;
} | [
"993273596@qq.com"
] | 993273596@qq.com |
0b0ab1115b8350f05b0b5eccfacd717cecedf46a | 6c1c92cb647616211041c60462b754350336ed74 | /Moteur2D/GameController.cpp | 51bb1abfa8f4bd287fbc633cfdf006847f4b12d6 | [] | no_license | PoignardAzur/CarresCouleur_2 | 55aadbb6c37683df50f3bf54f208d890083bae43 | c0e0ba164091036ded58516fdef16ac8237b13f5 | refs/heads/master | 2021-01-23T12:11:06.124308 | 2016-09-15T10:26:24 | 2016-09-15T10:26:24 | 30,531,259 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 762 | cpp |
#include "GameController.hpp"
GameController::GameController(uptrt<InputsAbstraction> userInputs, sf::RenderWindow* target)
{
m_userInputs = std::move(userInputs);
m_renderWindow = target;
if (target)
m_window.reset(new ObjectDrawer(target));
}
void GameController::update(float dt)
{
if (m_userInputs)
m_userInputs->update(dt);
interface().update(dt);
}
void GameController::display(float dt)
{
if (!interface().isDone())
{
m_window->clear();
interface().drawIn(*m_window, dt);
m_renderWindow->display();
}
}
DrawerAbstraction& GameController::renderingWindow()
{
return *(m_window.get());
}
InputsAbstraction& GameController::windowInputs()
{
return *(m_userInputs.get());
}
| [
"couteaubleu@gmail.com"
] | couteaubleu@gmail.com |
16d5541ed75ffe283ffebd4629e0fbf4602c1b4e | 600df3590cce1fe49b9a96e9ca5b5242884a2a70 | /third_party/pdfium/xfa/fxbarcode/datamatrix/BC_DefaultPlacement.cpp | 830df224ca93016cdd817df1d036c742e8f6a196 | [
"BSD-3-Clause",
"LGPL-2.0-or-later",
"GPL-1.0-or-later",
"MIT",
"Apache-2.0"
] | permissive | metux/chromium-suckless | efd087ba4f4070a6caac5bfbfb0f7a4e2f3c438a | 72a05af97787001756bae2511b7985e61498c965 | refs/heads/orig | 2022-12-04T23:53:58.681218 | 2017-04-30T10:59:06 | 2017-04-30T23:35:58 | 89,884,931 | 5 | 3 | BSD-3-Clause | 2022-11-23T20:52:53 | 2017-05-01T00:09:08 | null | UTF-8 | C++ | false | false | 5,289 | cpp | // Copyright 2014 PDFium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// Original code copyright 2014 Foxit Software Inc. http://www.foxitsoftware.com
// Original code is licensed as follows:
/*
* Copyright 2006 Jeremias Maerki.
*
* 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 "xfa/fxbarcode/datamatrix/BC_DefaultPlacement.h"
#include "xfa/fxbarcode/datamatrix/BC_Encoder.h"
CBC_DefaultPlacement::CBC_DefaultPlacement(CFX_WideString codewords,
int32_t numcols,
int32_t numrows) {
m_codewords = codewords;
m_numcols = numcols;
m_numrows = numrows;
m_bits.SetSize(numcols * numrows);
for (int32_t i = 0; i < numcols * numrows; i++) {
m_bits[i] = (uint8_t)2;
}
}
CBC_DefaultPlacement::~CBC_DefaultPlacement() {
m_bits.RemoveAll();
}
int32_t CBC_DefaultPlacement::getNumrows() {
return m_numrows;
}
int32_t CBC_DefaultPlacement::getNumcols() {
return m_numcols;
}
CFX_ByteArray& CBC_DefaultPlacement::getBits() {
return m_bits;
}
FX_BOOL CBC_DefaultPlacement::getBit(int32_t col, int32_t row) {
return m_bits[row * m_numcols + col] == 1;
}
void CBC_DefaultPlacement::setBit(int32_t col, int32_t row, FX_BOOL bit) {
m_bits[row * m_numcols + col] = bit ? (uint8_t)1 : (uint8_t)0;
}
FX_BOOL CBC_DefaultPlacement::hasBit(int32_t col, int32_t row) {
return m_bits[row * m_numcols + col] != 2;
}
void CBC_DefaultPlacement::place() {
int32_t pos = 0;
int32_t row = 4;
int32_t col = 0;
do {
if ((row == m_numrows) && (col == 0)) {
corner1(pos++);
}
if ((row == m_numrows - 2) && (col == 0) && ((m_numcols % 4) != 0)) {
corner2(pos++);
}
if ((row == m_numrows - 2) && (col == 0) && (m_numcols % 8 == 4)) {
corner3(pos++);
}
if ((row == m_numrows + 4) && (col == 2) && ((m_numcols % 8) == 0)) {
corner4(pos++);
}
do {
if ((row < m_numrows) && (col >= 0) && !hasBit(col, row)) {
utah(row, col, pos++);
}
row -= 2;
col += 2;
} while (row >= 0 && (col < m_numcols));
row++;
col += 3;
do {
if ((row >= 0) && (col < m_numcols) && !hasBit(col, row)) {
utah(row, col, pos++);
}
row += 2;
col -= 2;
} while ((row < m_numrows) && (col >= 0));
row += 3;
col++;
} while ((row < m_numrows) || (col < m_numcols));
if (!hasBit(m_numcols - 1, m_numrows - 1)) {
setBit(m_numcols - 1, m_numrows - 1, TRUE);
setBit(m_numcols - 2, m_numrows - 2, TRUE);
}
}
void CBC_DefaultPlacement::module(int32_t row,
int32_t col,
int32_t pos,
int32_t bit) {
if (row < 0) {
row += m_numrows;
col += 4 - ((m_numrows + 4) % 8);
}
if (col < 0) {
col += m_numcols;
row += 4 - ((m_numcols + 4) % 8);
}
int32_t v = m_codewords.GetAt(pos);
v &= 1 << (8 - bit);
setBit(col, row, v != 0);
}
void CBC_DefaultPlacement::utah(int32_t row, int32_t col, int32_t pos) {
module(row - 2, col - 2, pos, 1);
module(row - 2, col - 1, pos, 2);
module(row - 1, col - 2, pos, 3);
module(row - 1, col - 1, pos, 4);
module(row - 1, col, pos, 5);
module(row, col - 2, pos, 6);
module(row, col - 1, pos, 7);
module(row, col, pos, 8);
}
void CBC_DefaultPlacement::corner1(int32_t pos) {
module(m_numrows - 1, 0, pos, 1);
module(m_numrows - 1, 1, pos, 2);
module(m_numrows - 1, 2, pos, 3);
module(0, m_numcols - 2, pos, 4);
module(0, m_numcols - 1, pos, 5);
module(1, m_numcols - 1, pos, 6);
module(2, m_numcols - 1, pos, 7);
module(3, m_numcols - 1, pos, 8);
}
void CBC_DefaultPlacement::corner2(int32_t pos) {
module(m_numrows - 3, 0, pos, 1);
module(m_numrows - 2, 0, pos, 2);
module(m_numrows - 1, 0, pos, 3);
module(0, m_numcols - 4, pos, 4);
module(0, m_numcols - 3, pos, 5);
module(0, m_numcols - 2, pos, 6);
module(0, m_numcols - 1, pos, 7);
module(1, m_numcols - 1, pos, 8);
}
void CBC_DefaultPlacement::corner3(int32_t pos) {
module(m_numrows - 3, 0, pos, 1);
module(m_numrows - 2, 0, pos, 2);
module(m_numrows - 1, 0, pos, 3);
module(0, m_numcols - 2, pos, 4);
module(0, m_numcols - 1, pos, 5);
module(1, m_numcols - 1, pos, 6);
module(2, m_numcols - 1, pos, 7);
module(3, m_numcols - 1, pos, 8);
}
void CBC_DefaultPlacement::corner4(int32_t pos) {
module(m_numrows - 1, 0, pos, 1);
module(m_numrows - 1, m_numcols - 1, pos, 2);
module(0, m_numcols - 3, pos, 3);
module(0, m_numcols - 2, pos, 4);
module(0, m_numcols - 1, pos, 5);
module(1, m_numcols - 3, pos, 6);
module(1, m_numcols - 2, pos, 7);
module(1, m_numcols - 1, pos, 8);
}
| [
"enrico.weigelt@gr13.net"
] | enrico.weigelt@gr13.net |
90f29831b9325d80f49b09f314e502b7524de56b | 58fc34324e28598d208f8abc61b1e15ef9606aaf | /DemoDirectX/GameObjects/Player/PlayerFallingState.cpp | a1ec7b905bead9a6924e18a873add0383486e59c | [] | no_license | txbac98/Megaman-X3---UIT--SE102 | 2708c5827a60f4e4f5d12bdbb289166130e24b91 | 3c6b08ac6cf927ea2b47f35106ba2b111a63bc94 | refs/heads/master | 2021-10-09T07:36:41.170754 | 2018-12-23T16:30:48 | 2018-12-23T16:30:48 | 160,013,872 | 2 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 3,120 | cpp | ๏ปฟ#include "PlayerFallingState.h"
#include "Player.h"
#include "../../GameDefines/GameDefine.h"
#include "../../KeyGame.h"
PlayerFallingState::PlayerFallingState(PlayerData *playerData)
{
this->mPlayerData = playerData;
acceleratorY =15.0f;
acceleratorX = 8.0f;
//vแบญn tแปc x
if (this->mPlayerData->player->GetVx() == 0)
{
allowMoveX = false;
}
else
{
allowMoveX = true;
}
mPlayerData->player->allowMoveRight = true;
mPlayerData->player->allowMoveLeft = true;
this->mPlayerData->player->objectBottom = NULL;
}
PlayerFallingState::~PlayerFallingState()
{
}
void PlayerFallingState::Update(float dt)
{
//vแบญn tแปc rฦกi xuแปng
this->mPlayerData->player->AddVy(acceleratorY);
if (mPlayerData->player->GetVy() > PlayerDefine::MAX_JUMP_VELOCITY)
{
mPlayerData->player->SetVy(PlayerDefine::MAX_JUMP_VELOCITY);
}
//HandleKeyboard();
}
void PlayerFallingState::HandleKeyboard()
{
if (KEY->keyAttackPress) {
mPlayerData->player->SetState(new PlayerJumpingAndShootState(this->mPlayerData));
return;
}
if (KEY->keyRight && this->mPlayerData->player->allowMoveRight)
{
mPlayerData->player->SetReverse(false);
isLeftOrRightKeyPressed = true;
//di chuyen sang phai
if (this->mPlayerData->player->GetVx() < PlayerDefine::MAX_RUNNING_SPEED)
{
this->mPlayerData->player->AddVx(acceleratorX);
if (this->mPlayerData->player->GetVx() >= PlayerDefine::MAX_RUNNING_SPEED)
{
this->mPlayerData->player->SetVx(PlayerDefine::MAX_RUNNING_SPEED);
}
}
}
else if (KEY->keyLeft && this->mPlayerData->player->allowMoveLeft)
{
mPlayerData->player->SetReverse(true);
isLeftOrRightKeyPressed = true;
//di chuyen sang trai
if (this->mPlayerData->player->GetVx() > -PlayerDefine::MAX_RUNNING_SPEED)
{
this->mPlayerData->player->AddVx(-acceleratorX);
if (this->mPlayerData->player->GetVx() <= -PlayerDefine::MAX_RUNNING_SPEED)
{
this->mPlayerData->player->SetVx(-PlayerDefine::MAX_RUNNING_SPEED);
}
}
}
else
{
isLeftOrRightKeyPressed = false;
}
}
void PlayerFallingState::OnCollision(Entity * other, Entity::SideCollisions side) {
switch (side)
{
case Entity::NotKnow:
break;
case Entity::Left:
if ( KEY->keyLeft) //mแบทt xoay vร o bรชn trรกi
this->mPlayerData->player->SetState(new PlayerClingState(mPlayerData, other->GetBound().bottom));
break;
case Entity::BottomLeft:
break;
case Entity::Right:
if ( KEY->keyRight) //mแบทt xoay vร o bรชn phแบฃi
this->mPlayerData->player->SetState(new PlayerClingState(mPlayerData, other->GetBound().bottom));
break;
case Entity::BottomRight:
break;
case Entity::Top:
break;
case Entity::Bottom:
this->mPlayerData->player->SetState(new PlayerStandingState(this->mPlayerData));
break;
default:
break;
}
}
PlayerState::StateName PlayerFallingState::GetState()
{
return PlayerState::Falling;
}
| [
"txbac196@gmail.com"
] | txbac196@gmail.com |
f5b65ebf12d7a3bd021dfa040f56db287a9ae00f | d9a7603fcce655688ce25b8937c484226cabf2da | /Lab22/r1.cpp | feaa7fe49b1c11fa97b5dd8bfe242cb5a9bfc9d3 | [
"MIT"
] | permissive | fernnlcs/CppExercises | 91da9bad12494c3348419d32dd3c08c607b9d348 | 67c7a98a2c5695c41fb85f3216979ee67e5340cf | refs/heads/master | 2022-12-06T23:04:52.014327 | 2020-08-27T05:13:41 | 2020-08-27T05:13:41 | 290,676,262 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 248 | cpp | #include <iostream>
using namespace std;
int main() {
int x;
cout << "Digite um numero positivo ou negativo: ";
cin >> x;
cout << "O valor absoluto de " << x << " e ";
if (x >= 0)
{
cout << x;
}
else
{
cout << -x;
}
return 0;
}
| [
"fernnlcs@gmail.com"
] | fernnlcs@gmail.com |
29516e448b5ce310376c6bd60b939feb40590920 | be9f0a4e59ea93327006ab771a5bb4269c66fb5e | /Labs/Lab9/Vector3.h | c35994c55300e3501735ac483d6fc539ffb62af2 | [] | no_license | alvinquach/cs5550 | f99471b9a69d69623bb27e36848e8cffd12acb71 | bebe8023c98ae0a5adb644b7f8a34b37e9700068 | refs/heads/master | 2021-01-20T12:15:59.515816 | 2017-12-01T07:19:03 | 2017-12-01T07:19:03 | 101,705,792 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,176 | h | #ifndef VECTOR3_H
#define VECTOR3_H
#include <cmath>
// Vector3
class Vector3{
public:
float x,y,z;
void set(float dx, float dy, float dz){ x = dx; y = dy; z = dz;}
//void set(Vector3& v){ x = v.x; y = v.y; z = v.z;}
void set(Vector3 v){ x = v.x; y = v.y; z = v.z;}
void flip(){x = -x; y = -y; z = -z;} // reverse this vector
void setDiff(Point3& a, Point3& b)//set to difference a - b
{ x = a.x - b.x; y = a.y - b.y; z = a.z - b.z;}
void normalize()//adjust this vector to unit length
{
double sizeSq = x * x + y * y + z * z;
if(sizeSq < 0.0000001)
{
//cerr << "\nnormalize() sees vector (0,0,0)!";
return; // does nothing to zero vectors;
}
float scaleFactor = 1.0/(float)sqrt(sizeSq);
x *= scaleFactor; y *= scaleFactor; z *= scaleFactor;
}
Vector3(float xx, float yy, float zz){x = xx; y = yy; z = zz;}
Vector3(const Vector3& v){x = v.x; y = v.y; z = v.z;}
Vector3(){x = y = z = 0;} //default constructor
Vector3 cross(Vector3 b) //return this cross b
{
Vector3 c(y*b.z - z*b.y, z*b.x - x*b.z, x*b.y - y*b.x);
return c;
}
float dot(Vector3 b) // return this dotted with b
{return x * b.x + y * b.y + z * b.z;}
};
#endif | [
"alvinquach91@gmail.com"
] | alvinquach91@gmail.com |
2c58514819743f0f0b688c8f9cf357401b6598d5 | a3d6556180e74af7b555f8d47d3fea55b94bcbda | /chrome/browser/ui/views/global_media_controls/media_item_ui_legacy_cast_footer_view.cc | 71030637810017a35aafb8bf4cdcd97df7f9e3fc | [
"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 | 4,095 | cc | // Copyright 2021 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/ui/views/global_media_controls/media_item_ui_legacy_cast_footer_view.h"
#include "chrome/app/vector_icons/vector_icons.h"
#include "chrome/browser/feature_engagement/tracker_factory.h"
#include "chrome/browser/ui/global_media_controls/cast_media_notification_item.h"
#include "chrome/browser/ui/global_media_controls/media_notification_service.h"
#include "chrome/browser/ui/views/chrome_layout_provider.h"
#include "chrome/grit/generated_resources.h"
#include "components/feature_engagement/public/tracker.h"
#include "components/global_media_controls/public/media_item_manager.h"
#include "components/media_message_center/media_notification_item.h"
#include "components/media_router/browser/media_router.h"
#include "components/media_router/browser/media_router_factory.h"
#include "ui/base/l10n/l10n_util.h"
#include "ui/gfx/paint_vector_icon.h"
#include "ui/views/animation/ink_drop.h"
#include "ui/views/background.h"
#include "ui/views/border.h"
#include "ui/views/controls/button/label_button.h"
#include "ui/views/controls/highlight_path_generator.h"
#include "ui/views/layout/box_layout.h"
namespace {
constexpr auto kInsets = gfx::Insets::VH(6, 15);
constexpr gfx::Size kSize{400, 30};
constexpr auto kBorderInsets = gfx::Insets::VH(4, 8);
} // anonymous namespace
MediaItemUILegacyCastFooterView::MediaItemUILegacyCastFooterView(
base::RepeatingClosure stop_casting_callback)
: stop_casting_callback_(stop_casting_callback) {
DCHECK(!stop_casting_callback_.is_null());
auto* layout = SetLayoutManager(std::make_unique<views::BoxLayout>(
views::BoxLayout::Orientation::kHorizontal, kInsets));
layout->set_main_axis_alignment(views::BoxLayout::MainAxisAlignment::kStart);
layout->set_cross_axis_alignment(
views::BoxLayout::CrossAxisAlignment::kCenter);
SetPreferredSize(kSize);
stop_cast_button_ = AddChildView(std::make_unique<views::LabelButton>(
base::BindRepeating(&MediaItemUILegacyCastFooterView::StopCasting,
base::Unretained(this)),
l10n_util::GetStringUTF16(
IDS_GLOBAL_MEDIA_CONTROLS_STOP_CASTING_BUTTON_LABEL)));
const int radius = ChromeLayoutProvider::Get()->GetCornerRadiusMetric(
views::Emphasis::kMaximum, kSize);
views::InstallRoundRectHighlightPathGenerator(stop_cast_button_,
gfx::Insets(), radius);
views::InkDrop::Get(stop_cast_button_)
->SetMode(views::InkDropHost::InkDropMode::ON);
stop_cast_button_->SetFocusBehavior(FocusBehavior::ALWAYS);
stop_cast_button_->SetBorder(views::CreatePaddedBorder(
views::CreateRoundedRectBorder(1, radius, foreground_color_),
kBorderInsets));
UpdateColors();
}
MediaItemUILegacyCastFooterView::~MediaItemUILegacyCastFooterView() = default;
views::Button*
MediaItemUILegacyCastFooterView::GetStopCastingButtonForTesting() {
return stop_cast_button_;
}
void MediaItemUILegacyCastFooterView::OnColorsChanged(SkColor foreground,
SkColor background) {
if (foreground == foreground_color_ && background == background_color_)
return;
foreground_color_ = foreground;
background_color_ = background;
UpdateColors();
}
void MediaItemUILegacyCastFooterView::StopCasting() {
stop_cast_button_->SetEnabled(false);
stop_casting_callback_.Run();
}
void MediaItemUILegacyCastFooterView::UpdateColors() {
// Update background.
SetBackground(views::CreateSolidBackground(background_color_));
// Update button icon.
stop_cast_button_->SetEnabledTextColors(foreground_color_);
views::InkDrop::Get(stop_cast_button_)->SetBaseColor(foreground_color_);
const int radius = ChromeLayoutProvider::Get()->GetCornerRadiusMetric(
views::Emphasis::kMaximum, kSize);
stop_cast_button_->SetBorder(views::CreatePaddedBorder(
views::CreateRoundedRectBorder(1, radius, foreground_color_),
kBorderInsets));
}
| [
"chromium-scoped@luci-project-accounts.iam.gserviceaccount.com"
] | chromium-scoped@luci-project-accounts.iam.gserviceaccount.com |
bd0e0e380a5a7347759c9187c7eacb0c60cab870 | 61deafb2dcf4820d46f2500d12497a89ff66e445 | /1342.cpp | 844fb3774589ee44546321ef4891ec857c0b431f | [] | no_license | Otrebus/timus | 3495f314587beade3de67890e65b6f72d53b3954 | 3a1dca43dc61b27c8f903a522743afeb69d38df2 | refs/heads/master | 2023-04-08T16:54:07.973863 | 2023-04-06T19:59:07 | 2023-04-06T19:59:07 | 38,758,841 | 72 | 40 | null | null | null | null | UTF-8 | C++ | false | false | 2,066 | cpp | /* 1342. Enterprise - http://acm.timus.ru/problem.aspx?num=1342
*
* Strategy:
* Dynamic programming where we use subsolutions for using the first n workshops making
* a total of m brooms - see comments below.
*
* Performance:
* O(NMK), with K being the maximum number of brooms any workshop can produce, runs the
* tests in 0.281s using 8,300KB memory.
*/
#include <iostream>
#include <cmath>
#include <cstdio>
#include <iomanip>
#include <array>
struct {
int k;
double p, q, r;
} W[1001];
int S[1001];
double C[1001][1001]; // The subsolutions
double inf = std::numeric_limits<double>::infinity();
int main() {
int N, M;
scanf("%d %d", &N, &M);
for(int i = 1; i <= N; i++) {
scanf("%d %lf %lf", &W[i].k, &W[i].p, &W[i].q);
W[i].r = 0.5*(W[i].q - W[i].p)/double(W[i].k-1.0); // Calculates part of the integral ahead
S[i] = S[i-1] + W[i].k; // The number of brooms all workshops up to this can produce
}
for(int n = 0; n <= N; n++)
for(int m = 0; m <= M; m++)
C[m][n] = inf;
C[0][0] = 0;
for(int n = 1; n <= N; n++) {
for(int m = std::max(std::min(W[n].k, M - (S[N] - S[n])), 0); m <= std::min(S[n], M); m++) {
// The max total production in workshops up to n depends on how much we need in the
// rest of the workshops, and how much we can actually produce
double min = inf;
for(int i = std::max(m - S[n-1], 0); i <= std::min(W[n].k, m); i++)
// For each number of brooms i that makes sense to produce in the workshop, update
// the optimal value of C[m][n] given C[m-i][n-1]
min = std::min(C[m-i][n-1] + W[n].p*i + (i <= 1 ? 0.0 : i*(i-1.0)*W[n].r), min);
C[m][n] = min;
}
}
std::cout << std::fixed << std::setprecision(2);
if(C[M][N] == inf) {
while(C[M][N] == inf)
M--;
std::cout << "Maximum possible amount: " << M << std::endl;
}
std::cout << "Minimum possible cost: " << C[M][N];
}
| [
"otrebus@gmail.com"
] | otrebus@gmail.com |
4d14404326f5082f18582314603ae1ff3f82d037 | 78b9947ea0a6d44f4d7b27ce392476a56ee9bcd6 | /mango-library/src/epic/driver.cpp | f07e949c4c75b4489ba09f8efd25d051181aae46 | [
"MIT"
] | permissive | fengjixuchui/mango-library | 04b2f6951da06f2aeeb69eeef8a1114f12232401 | f36a69f0457ecd89266e92a12b5a4a29c66bb52a | refs/heads/master | 2020-12-27T13:38:34.538648 | 2020-08-10T03:47:33 | 2020-08-10T03:47:33 | 237,921,104 | 0 | 0 | MIT | 2020-08-10T03:47:35 | 2020-02-03T08:47:13 | null | UTF-8 | C++ | false | false | 4,039 | cpp | #include "../../include/epic/driver.h"
#include "../../include/misc/error_codes.h"
#include "../../include/misc/scope_guard.h"
namespace mango {
// open a handle to the driver
void Driver::setup(const std::string_view name, const SetupOptions& options) {
this->release();
// std::string_view **could** be not null-terminated
const std::string null_terminated_name{ name };
// open handle
this->m_handle = CreateFileA(null_terminated_name.c_str(), options.access, 0, nullptr, OPEN_EXISTING, options.attributes, nullptr);
if (this->m_handle == INVALID_HANDLE_VALUE)
throw InvalidFileHandle{ mango_format_w32status(GetLastError()) };
this->m_is_valid = true;
}
// close the handle to the driver
void Driver::release() noexcept {
if (!this->m_is_valid)
return;
// dont throw
try {
CloseHandle(this->m_handle);
} catch (...) {}
this->m_is_valid = false;
}
// IRP_MJ_WRITE
uint32_t Driver::write(const void* const buffer, const uint32_t size) const {
DWORD num_bytes_written{ 0 };
if (!WriteFile(this->m_handle, buffer, size, &num_bytes_written, nullptr))
throw FailedToWriteFile{ mango_format_w32status(GetLastError()) };
return num_bytes_written;
}
// IRP_MJ_READ
uint32_t Driver::read(void* const buffer, const uint32_t size) const {
DWORD num_bytes_read{ 0 };
if (!ReadFile(this->m_handle, buffer, size, &num_bytes_read, nullptr))
throw FailedToReadFile{ mango_format_w32status(GetLastError()) };
return num_bytes_read;
}
// IRP_MJ_DEVICE_CONTROL
uint32_t Driver::iocontrol(const uint32_t control_code, void* const in_buffer,
const uint32_t in_buffer_size, void* const out_buffer, const uint32_t out_buffer_size) const {
DWORD bytes_returned{ 0 };
if (!DeviceIoControl(this->m_handle, control_code, in_buffer, in_buffer_size, out_buffer, out_buffer_size, &bytes_returned, nullptr))
throw IoControlFailed{ mango_format_w32status(GetLastError()) };
return bytes_returned;
}
// register and start a service using the service control manager
SC_HANDLE create_and_start_service(const std::string_view service_name, const std::string_view file_path) {
const auto sc_manager{ OpenSCManagerA(nullptr, nullptr, SC_MANAGER_CREATE_SERVICE) };
if (!sc_manager)
throw FailedToOpenServiceControlManager{ mango_format_w32status(GetLastError()) };
// close the service control manager handle
const ScopeGuard _guardone{ &CloseServiceHandle, sc_manager };
const std::string null_terminated_name(service_name),
null_terminated_path(file_path);
// create our service
const auto service{ CreateServiceA(
sc_manager,
null_terminated_name.c_str(),
null_terminated_name.c_str(),
SERVICE_START | SERVICE_STOP | DELETE,
SERVICE_KERNEL_DRIVER,
SERVICE_DEMAND_START,
SERVICE_ERROR_IGNORE,
null_terminated_path.c_str(),
nullptr,
nullptr,
nullptr,
nullptr,
nullptr
) };
if (!service)
throw FailedToCreateService{ mango_format_w32status(GetLastError()) };
// if StartService fails, delete the service and close the handle
ScopeGuard _guardtwo{ &CloseServiceHandle, service },
_guardthree{ &DeleteService, service };
// start the service
if (!StartServiceA(service, 0, nullptr))
throw FailedToStartService{ mango_format_w32status(GetLastError()) };
// no errors, cool
_guardtwo.cancel(_guardthree);
return service;
}
// stop and remove a running service
void stop_and_delete_service(const SC_HANDLE service) {
// if we throw an exception, do not leak the handle
const ScopeGuard _guard{ &CloseServiceHandle, service };
// stop the service
SERVICE_STATUS _unused{};
if (!ControlService(service, SERVICE_CONTROL_STOP, &_unused))
throw FailedToStopService{ mango_format_w32status(GetLastError()) };
// delete the service
if (!DeleteService(service))
throw FailedToDeleteService{ mango_format_w32status(GetLastError()) };
}
} // namespace mango | [
"26609800+jonomango@users.noreply.github.com"
] | 26609800+jonomango@users.noreply.github.com |
d7d8a1dbe426e1502f48fb73b851f88db5dbd48a | a6e0e2de1c86964f5f9c0f9765d8d9a1b3da548b | /CMake/teca_platform_tests.cpp | 14c16ade539a03a2672b78b54f8388de2dd2938f | [
"BSD-3-Clause-LBNL"
] | permissive | LBL-EESA/TECA | 056b1b7859d87f8c55d2267f90c78c548826b931 | c78d39b05623fb33cc5487e038a6441ce8a44c55 | refs/heads/develop | 2023-08-31T13:44:45.918534 | 2023-07-25T15:13:03 | 2023-07-25T15:13:03 | 48,189,266 | 52 | 21 | NOASSERTION | 2023-09-11T23:51:12 | 2015-12-17T17:46:48 | C++ | UTF-8 | C++ | false | false | 569 | cpp | #ifdef CXX11_REGEX_TEST
#include <regex>
#include <string>
#include <iostream>
int main(int argc, char **argv)
{
try
{
std::string s("this subject has a submarine as a subsequence");
std::regex e("\\b(sub)([^ ]*)"); // matches words beginning by "sub"
std::smatch m;
int n_matches = 0;
while (std::regex_search (s,m,e))
{
++n_matches;
s = m.suffix().str();
}
if (n_matches == 3)
return 1;
}
catch (std::regex_error &err)
{}
return 0;
}
#endif
| [
"bloring@lbl.gov"
] | bloring@lbl.gov |
0baa91e28870b2c3580f75b0740b670529da497e | f90bec02326b0154502f05d2223c7ed4cdc75de8 | /tugasGueh.cpp | 351230121d9b60195a6f535640f59a02fe268704 | [] | no_license | ArdihamsyahJR/tugasBosque | 599352b002714be4bc5d29db9c5d1e893556c374 | 8893f955c862abcf4177a16aff3798dbff210a88 | refs/heads/master | 2021-07-05T00:12:21.463214 | 2017-09-29T07:17:44 | 2017-09-29T07:17:44 | 105,239,530 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 130 | cpp | #include <iostream>
using namespace std ;
int main(){
cout <<"halo dunia" << endl ;
cout << "ini program C++ pertama saya" ;
}
| [
"32383340+ArdihamsyahJR@users.noreply.github.com"
] | 32383340+ArdihamsyahJR@users.noreply.github.com |
6e8c3826c248492fc9e7a2ee1e4949281930cfd3 | d324dafd7b383d1fccac2e6f954d2c35264d84d8 | /multigpu_graphics_attila/src/tools/Trace Viewer/DataManager.cpp | c39f630a01622d415f6399faed387c75dd4c1039 | [
"BSD-3-Clause",
"BSD-2-Clause-Views",
"MIT"
] | permissive | flair2005/Scalable-Multi-GPU-Rendering | 847efbaddd7c091c7bea20ebec1f22fcd5d80022 | 1fe0fa74cee5891424db73654551335a7fd5380c | refs/heads/main | 2023-02-06T07:57:02.429875 | 2020-12-29T01:06:10 | 2020-12-29T01:06:10 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,390 | cpp | #include "DataManager.h"
#include <windows.h>
#define MSG(title,msg) MessageBox( NULL, msg, title, MB_OK );
#define SHOWDATA_SIZE 40
#define SHOWDATA { char __buf[SHOWDATA_SIZE];\
str.readAndPutback( __buf, sizeof(__buf)-1 );\
__buf[SHOWDATA_SIZE-1] = 0;\
MSG( "buf", __buf );\
}
DataManager::SigIdentification::SigIdentification( const char* name, int nSlot )
{
char buffer[10];
originalSignalName = new char[strlen(name)+1];
strcpy( originalSignalName, name );
sprintf( buffer, ".%d", nSlot );
simpleSignalName = new char[strlen(name)+strlen(buffer)+2];
strcpy( simpleSignalName, name );
strcat( simpleSignalName, buffer );
}
DataManager::SigIdentification::~SigIdentification()
{
delete[] originalSignalName;
delete[] simpleSignalName;
}
using namespace std;
const char* DataManager::getSimpleSignalName( int simpleSignalId ) const
{
return v[simpleSignalId]->simpleSignalName;
}
DataManager::DataManager() : totalCyclesInFile(-1)
{
}
int DataManager::loadData( const char* traceFilePath, int maxCycles )
{
// maxCycles ignored in this version ( 0.4 beta )
if ( !str.open( traceFilePath ) )
return -1;
str.skipLines( 4 );
str.readSignalInfo( sil );
// Compute simple signal objects
// ex: signal with bw 2 is converted in two simple signals
int i, j;
for ( i = 0; i < sil.size(); i++ ) {
const SignalInfo* si = sil.get( i );
const char* sName = si->getSignalName();
for ( j = 0; j < si->getBw(); j++ )
v.push_back( new SigIdentification( sName, j ) );
}
// initialize number of rows for CyclePages ( set to simpleSignals count )
CyclePage::setRows( v.size() );
// create cache
cache = new CyclePageCache( 5 );
// load first page ( not necessary )
//CyclePage* cp = new CyclePage( 0 );
//loadData( cp );
CycleInfo::setSignalInfoList( &sil ); // Configure CycleInfo with current SignalInfoList
vOffset.push_back( str.getPosition() );
return 0;
}
int DataManager::getCycles()
{
if ( totalCyclesInFile == -1 ) // computed only once
totalCyclesInFile = str.countCyclesInfo( str.getFileName() );
return totalCyclesInFile;
}
const SimpleSignalInfo* DataManager::getData( int x, int y )
{
int idPage = y / CyclePage::getPageCapacity(); // compute idPage
int relativeY = y % CyclePage::getPageCapacity(); // compute page offset
CyclePage* cp = cache->getPage( idPage ); // find out if the page is in cache
if ( cp != NULL ) // hit ( page is in cache )
return cp->getData( x, relativeY );
// miss ( page is not in cache )
cp = cache->getFreePage( idPage ); // obtains a free page and asociates its identifier
// find file position
if ( vOffset.size() > idPage ) // offset was saved previously ( directly positioning )
str.setPosition( vOffset[idPage] );
else { // find offset page
/*
MSG( "find offset page", "NOT IMPLEMENTED ( accept implies exiting )" );
*/
int ini = vOffset.size() - 1;
// set position at last known offset
str.setPosition( vOffset[ini] );
while ( ini++ < idPage )
vOffset.push_back( skipPage() ); // save offsets found through the file
str.setPosition( vOffset[vOffset.size()-1] );
}
loadPage( cp ); // load data for this page
vOffset.push_back( str.getPosition() ); // save next offset to increase sequential accesses
return cp->getData( x, relativeY ); // returns data
}
void DataManager::dump() const
{
/*
int i, j;
for ( j = 0; j < cycles; j++ ) {
cout << "Cycle " << j << " infomation:" << endl;
for ( i = 0; i < v.size(); i++ ) {
if ( ssArray[i][j] != NULL ) {
cout << "Signal: " << v[i]->simpleSignalName << endl;
cout << " Cookies: ";
int nCookies;
const int* cookies = ssArray[i][j]->getCookies( nCookies );
for ( int k = 0; k < nCookies; k++ ) {
cout << cookies[k];
if ( k != nCookies - 1 ) cout << ":";
}
cout << " Color: " << ssArray[i][j]->getColor();
const char* info = ssArray[i][j]->getInfo();
if ( info )
cout << " Info: " << info << endl;
else
cout << endl;
//cout << endl;
}
}
cout << "-----------------------------------------" << endl;
}
*/
}
int DataManager::skipPage()
{
int pageCycles = CyclePage::getPageCapacity();
for ( int i = 0; i < pageCycles; i++ )
str.skipCycleInfo();
return str.getPosition();
}
void DataManager::loadPage( CyclePage* page )
{
// load data from file to CyclePage
//SHOWDATA;
cout << "*********************** LOADING PAGE *************************** " << endl;
CycleInfo ci;
int PAGE_CYCLES = page->getPageCapacity();
int cycles = 0;
int i, j;
while ( cycles < PAGE_CYCLES && str.readCycleInfo( ci ) ) {
cycles++;
int vPosition = 0;
int cycle = ci.getCycle(); // cycle is the horizontal position
for ( i = 0; i < sil.size(); i++ ) {
const SignalInfo* si = sil.get( i ); // gets general signal information
SignalContent* sc = ci.getSignalContent( i ); // gets signal's content for a particular cycle
int nsc = sc->countSignalContents();
for ( j = 0; j < si->getBw(); j++ ) { // forall slots
if ( j < nsc ) { // only get data from slots with data ( first nsc slots )
int nCookies;
const int* cookies = sc->getCookieList( j, nCookies );
page->setData( vPosition, cycle % CyclePage::getPageCapacity(),
new SimpleSignalInfo( sc->getColor(), cookies, nCookies, sc->getInfo(j) ) );
}
vPosition++;
}
}
}
}
| [
"renxiaowei66@gmail.com"
] | renxiaowei66@gmail.com |
9393f3b1a4cc261c4b5e70c960d30cb1907a840c | 26ae957a218ba65446d7013f74dc827fbd211952 | /src/M5TreeView.cpp | c47291d6ba36e8e6d93eec05c1fcc4134ff51896 | [
"MIT"
] | permissive | k1nsenka/M5Stack_TreeView | 1f6a4786213913ad998458817ee6a1f920ebc084 | 0b7fba8ada5ffc775addf1d49b645c7f5495b035 | refs/heads/master | 2022-11-11T15:30:45.806683 | 2020-06-27T14:18:59 | 2020-06-27T14:18:59 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,060 | cpp | #include <M5TreeView.h>
#include <M5PLUSEncoder.h>
#include <M5FACESEncoder.h>
#include <M5JoyStick.h>
#undef min
#include <algorithm>
void M5TreeView::begin() {
for (uint16_t i = 0; i != Items.size(); ++i) {
Items[i]->visible = true;
}
destRect.w = 0; // root item hidden
destRect.h = 0;
destRect.y = clientRect.y;
destRect.x = clientRect.x - treeOffset;
updateDest();
updateButtons();
setFocusItem(Items[0]);
update(true);
}
static char facesKey = 0xff;
static char facesPrev = 0xff;
static bool flgFACESKB = false;
M5TreeView::eCmd M5TreeView::checkKB(char key) {
switch ((uint8_t)key) {
case 'w': case 'W': case 0x80: case 0xB5: return eCmd::PREV;
case 'a': case 'A': case 0x81: case 0xB4: case 0x08: return eCmd::BACK;
case 's': case 'S': case 0x82: case 0xB6: return eCmd::NEXT;
case 'd': case 'D': case 0x83: case 0xB7: case 0x20: return eCmd::ENTER;
}
return eCmd::NONE;
}
#ifdef ARDUINO_ODROID_ESP32
M5TreeView::eCmd M5TreeView::checkInput() {
_msec = millis();
M5.update();
eCmd res = eCmd::NONE;
bool press = M5.BtnA.isPressed()
|| M5.BtnB.isPressed()
|| M5.JOY_X.isPressed()
|| M5.JOY_Y.isPressed();
bool canRepeat = _repeat == 0 || (_msec - _msecLast + _repeat) >= (1 < _repeat ? msecRepeat : msecHold);
if (canRepeat) {
if (M5.BtnA.isPressed()) { res = eCmd::HOLD; }
else if (M5.BtnA.wasReleased() || (M5.JOY_X.isAxisPressed() == DPAD_V_HALF)) { ++_repeat; res = eCmd::ENTER; }
else if (M5.BtnB.wasReleased() || (M5.JOY_X.isAxisPressed() == DPAD_V_FULL)) { ++_repeat; res = eCmd::BACK; }
else if (M5.JOY_Y.isAxisPressed() == DPAD_V_HALF ) { ++_repeat; res = eCmd::NEXT; }
else if (M5.JOY_Y.isAxisPressed() == DPAD_V_FULL ) { ++_repeat; res = eCmd::PREV; }
}
if (!press) {
_repeat = 0;
}
if (res != eCmd::NONE) {
_msecLast = millis();
}
return res;
}
#else
M5TreeView::eCmd M5TreeView::checkInput() {
bool btnALong = M5.BtnA.pressedFor(msecHold);
_msec = millis();
M5.update();
eCmd res = eCmd::NONE;
Button& btnB(swapBtnBC ? M5.BtnC : M5.BtnB);
Button& btnC(swapBtnBC ? M5.BtnB : M5.BtnC);
bool press = M5.BtnA.isPressed() || btnB.isPressed() || btnC.isPressed();
bool canRepeat = _repeat == 0 || (_msec - _msecLast + _repeat) >= (1 < _repeat ? msecRepeat : msecHold);
if (canRepeat) {
if (btnB.isPressed()) { res = eCmd::HOLD; }
else if (M5.BtnA.wasReleased() && !btnALong) { res = eCmd::BACK; }
else if (btnC.isPressed() ) { ++_repeat; res = eCmd::NEXT; }
else if (btnB.wasReleased()) { res = eCmd::ENTER; }
else if (btnALong) { ++_repeat; res = eCmd::PREV; }
}
if (res == eCmd::NONE
&& useFACES && Wire.requestFrom(0x08, 1)) {
while (Wire.available()){
facesPrev = facesKey;
facesKey = Wire.read();
if (facesKey == 0) { flgFACESKB = true; }
else {
if (facesKey == 0xff) { flgFACESKB = false; }
else press = true;
if (flgFACESKB) {
res = checkKB(facesKey);
} else {
if (facesKey != 0xff && canRepeat) {
if ( 0 == (facesKey & 0x01) ) { res = eCmd::PREV; ++_repeat; }
else if (0 == (facesKey & 0x02) ) { res = eCmd::NEXT; ++_repeat; }
}
if (0 == (facesKey & 0x08) || 0 == (facesKey & 0x10)) { res = eCmd::HOLD; }
else if ((0 != (facesKey & 0x04))&&(0 == (facesPrev & 0x04))) { res = eCmd::BACK; }
else if ((0 != (facesKey & 0x20))&&(0 == (facesPrev & 0x20))) { res = eCmd::BACK; }
else if ((0 != (facesKey & 0x08))&&(0 == (facesPrev & 0x08))) { res = eCmd::ENTER; }
else if ((0 != (facesKey & 0x10))&&(0 == (facesPrev & 0x10))) { res = eCmd::ENTER; }
}
}
}
}
if (res == eCmd::NONE
&& useCardKB && Wire.requestFrom(0x5F, 1)) {
while (Wire.available()){
char key = Wire.read();
if (key == 0) { continue; }
press = true;
res = checkKB(key);
}
}
if (res == eCmd::NONE
&& usePLUSEncoder && PLUSEncoder.update()) {
if ( PLUSEncoder.wasUp()) { res = eCmd::PREV; }
else if (PLUSEncoder.wasDown()) { res = eCmd::NEXT; }
else if (PLUSEncoder.wasHold()) { res = eCmd::BACK; }
else if (PLUSEncoder.wasClicked()) { res = eCmd::ENTER; }
}
if (res == eCmd::NONE
&& useFACESEncoder && FACESEncoder.update()) {
if ( FACESEncoder.wasUp()) { res = eCmd::PREV; }
else if (FACESEncoder.wasDown()) { res = eCmd::NEXT; }
else if (FACESEncoder.wasHold()) { res = eCmd::BACK; }
else if (FACESEncoder.wasClicked()) { res = eCmd::ENTER; }
}
if (res == eCmd::NONE
&& useJoyStick && JoyStick.update()) {
if (!JoyStick.isNeutral()) {
press = true;
if (canRepeat) {
++_repeat;
if (JoyStick.isUp() ) { res = eCmd::PREV; }
if (JoyStick.isDown() ) { res = eCmd::NEXT; }
if (JoyStick.wasLeft() ) { res = eCmd::BACK; }
if (JoyStick.wasRight()) { res = eCmd::ENTER; }
}
}
if (JoyStick.wasClicked()) { res = eCmd::ENTER; }
if (JoyStick.wasHold()) { res = eCmd::BACK; }
}
if (!press) {
_repeat = 0;
}
if (res != eCmd::NONE) {
_msecLast = millis();
}
return res;
}
#endif
MenuItem* M5TreeView::update(bool redraw) {
if (millis() - _msec < 16) {
uint32_t freq = getCpuFrequencyMhz();
if (useLowClockDelay) setCpuFrequencyMhz(getXtalFrequencyMhz() / 4);
delay(16 - (millis() - _msec));
if (useLowClockDelay) setCpuFrequencyMhz(freq);
}
redraw |= _redraw;
_redraw = false;
eCmd cmd = checkInput();
if (cmd != eCmd::NONE || M5.BtnA.wasPressed() || M5.BtnA.wasReleased() || redraw) {
updateButtons();
}
#ifndef ARDUINO_ODROID_ESP32
_btnDrawer.draw(redraw);
#endif
bool moveFocus = (!_cursorRect.equal(focusItem->destRect));
if (move(cmd != eCmd::NONE) || moveFocus || redraw) {
erase(false);
if (moveFocus) {
const Rect16& c = _cursorRect;
Rect16 r = cmd != eCmd::NONE ? focusItem->destRect : c.mixRect(focusItem->destRect);
draw(redraw, &r, &_cursorRect);
_cursorRect = r;
} else {
draw(redraw, &_cursorRect);
}
}
MenuItem* oldFocus = focusItem;
MenuItem* res = NULL;
switch (cmd) {
case eCmd::NONE: break;
case eCmd::PREV: focusPrev(); break;
case eCmd::NEXT: focusNext(); break;
case eCmd::BACK: focusBack();
res = focusItem;
if (res == this) focusItem = oldFocus;
break;
case eCmd::ENTER: case eCmd::HOLD:
{
Rect16 rtmp = focusItem->rect;
rtmp = clientRect.intersect(rtmp);
M5.Lcd.drawRect(rtmp.x, rtmp.y, rtmp.w, rtmp.h, frameColor[1]);
if (cmd == eCmd::ENTER) {
res = focusItem;
_redraw = focusEnter();
if (_redraw) {
updateDest();
erase(true);
focusItem->onFocus();
}
}
}
break;
}
if (oldFocus != focusItem) {
scrollTarget(focusItem);
}
if (focusItem) focusItem->onFocusLoop();
return res;
}
| [
"42724151+lovyan03@users.noreply.github.com"
] | 42724151+lovyan03@users.noreply.github.com |
431c8161c1ec02837758f5d826b51a1969a38127 | 780dbced67262f3b104550c0ade52b2c5c411f0c | /ํ ๋งํ 2.cpp | a569c880a447b5d4aa56ef55b26285ca2fa7a1a6 | [] | no_license | jhycj/euler | 90290a11054fe569836bdb2288af6e431397e587 | b9240bd1bed40c98223d472618534802bbaf781d | refs/heads/master | 2022-11-28T17:42:38.736750 | 2020-08-11T07:51:07 | 2020-08-11T07:51:07 | 201,714,374 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,669 | cpp | #include<stdio.h>
#define INF 987654321
int n;
int m;
int h;
int map[101][101][101];
int Q[3000000];
int rear;
int front;
void bfs (void){
int i;
int dz[6] = {0, 0, 0, 0, 1, -1};
int dy[6] = {0, 1, 0, -1, 0, 0};
int dx[6] = {1, 0, -1, 0, 0, 0};
int z; int y; int x;
int tz; int ty; int tx;
front = 0;
while(rear>front){
z= Q[front];
front++;
y= Q[front];
front++;
x = Q[front];
front++;
for(i=0; i<6; i++){
tz = z+dz[i];
ty = y+dy[i];
tx = x+dx[i];
if(tz>= 1 && tz<= h && ty>=1 && ty<=n && tx>=1 && tx<=m && map[tz][ty][tx] > map[z][y][x]+1){
Q[rear] = tz;
rear++;
Q[rear]= ty;
rear++;
Q[rear] = tx;
rear++;
map[tz][ty][tx] = map[z][y][x] +1;
}
}
}
}
int get_maximum(void){
int i;
int j;
int k;
int max;
max = map[1][1][1];
for(k=1; k<=h; k++){
for(i=1; i<=n; i++){
for(j=1; j<=m; j++){
if(max<=map[k][i][j]){
max = map[k][i][j];
}
}
}
}
return max;
}
void get_answer(void){
int answer;
answer = get_maximum();
if(answer==0){ // ์ฒ์๋ถํฐ ์ต์ด์๋ ์ํฉ
printf("%d", 0);
}
else if(answer==INF){ //๋ชจ๋ ์ต์ง ๋ชปํ๋ ์ํฉ
printf("%d", -1);
}
else{
printf("%d", answer);
}
}
int main(){
int i; int j; int k;
int tmp;
int count = 0;
int bar=0;
scanf("%d %d %d", &m, &n, &h); //๊ฐ๋ก, ์ธ๋ก, ๋์ด
for(k=1; k<=h; k++){
for(i=1; i<=n; i++){
for(j=1; j<=m; j++){
scanf("%d", &tmp);
if(tmp==0){ //์์ง ์ต์ง ์์ ํ ๋งํ
map[k][i][j] = INF;
}
else if(tmp==1){ //์ต์ ํ ๋งํ
map[k][i][j] = 0;
Q[rear] = k;
rear++;
Q[rear] = i;
rear++;
Q[rear] = j;
rear++;
count++;
}
else if(tmp==-1){
map[k][i][j] = -1;
bar++;
}
}
}
}
bfs();
get_answer();
/*for(k= 1; k<=h; k++){
for(i=1; i<=n; i++){
for(j=1; j<=m; j++){
printf("%d ",map[k][i][j]);
}
printf("\n");
}
printf("\n");
}*/
return 0;
}
| [
"jhycj@naver.com"
] | jhycj@naver.com |
f61a560f13c820bba4c02df833b29bcce0915386 | 3afb0ea6c3001af11224ee34868e5d6876117add | /Bronze/Sorting/why did the cows cross the road 3/main.cpp | 5a475f27d6863e2d044b641de5d5bdb6d2c28697 | [] | no_license | Abdelrahman-Yehia/Usaco-Guide-Solutions | ba1c940c112fb22147167ef45a42e318d1f4ecfd | e7062b40241b23e258455806c8b5c8cf0f754622 | refs/heads/main | 2023-07-25T03:47:03.718192 | 2021-09-03T06:25:33 | 2021-09-03T06:25:33 | 370,804,519 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,917 | cpp | #include <bits/stdc++.h>
#include <string>
using namespace std;
#define pb push_back
#define F first
#define S second
#define rep(i,n) for(int i = 0; i < (n); i++)
#define input freopen("input.in","r",stdin)
#define output freopen("output.out","w",stdout)
#define ordered_set tree<int, null_type,less<int>, rb_tree_tag,tree_order_statistics_node_update>
using ll = long long;
using ld = long double;
using ul = unsigned long long;
using ii = pair<int, int>;
const ll mod7 = 1000000007,mod1 = 1000000000,OO = 0x3f3f3f3f;
const ld EPS = 1e-7;
double Pi=acos(-1);
const ld rad=Pi/180.0;
long long power(long long a, long long b, ll mod)
{
if(!b)
return 1ll;
if(b == 1)
return a%mod;
long long r = power(a, b/2ll,mod)%mod;
if(b%2ll)
return ((r*(a%mod)%mod)*r)%mod;
else
return (r*r)%mod;
}
ll nCr (ll n,ll m)
{
return(m == 0)?1:n*nCr(n-1,m-1)/m;
}
bool checkDivisibility(ll n, int digit)
{
return (digit == 0|| (digit != 0 && n % digit == 0));
}
bool allDigitsDivide(ll n)
{
ll temp = n;
while (temp > 0)
{
ll digit = temp % 10;
if (!(checkDivisibility(n, digit)))
return false;
temp /= 10;
}
return true;
}
int gcd(int a, int b)
{
if (b == 0)
return a;
return gcd(b, a % b);
}
int lcm(int a, int b)
{
return (a / gcd(a, b)) * b;
}
bool comp(int a,int b)
{
return a< b;
}
/**************************************************/
int main()
{
freopen("cowqueue.in","r",stdin);
freopen("cowqueue.out","w",stdout);
int n;
cin>>n;
vector<ii> cows(n);
rep(i,n){
cin>>cows[i].F>>cows[i].S;
}
sort(cows.begin(),cows.end());
ll current = 0;
rep(i,n){
if(current<cows[i].F){
current = cows[i].F + cows[i].S;
}
else current += cows[i].S;
}
cout<<current;
}
| [
"66071636+Akayehia@users.noreply.github.com"
] | 66071636+Akayehia@users.noreply.github.com |
ca0076a5c68aa2608bb69f0be1447768c1d5561a | ff379b7f81d8c96ff500cdeb461889506644a830 | /tinycl/rtl/tinycl_rtl_integer.cpp | 2623af9f95851041ead95b09d0bac294c5f80401 | [] | no_license | eval1749/tiny-common-lisp | 500c2bb68d32e308ccdee1041e72275edff5d0c7 | da408784dd9f5e49f7733ad8338d3c8969f41e89 | refs/heads/master | 2020-05-17T08:39:23.795312 | 2012-04-30T11:28:29 | 2012-04-30T11:28:29 | 23,464,880 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,805 | cpp | #include "precomp.h"
//////////////////////////////////////////////////////////////////////////////
//
// TinyCl - Runtime - Integer
// tinycl_integer.cpp
//
// Copyright (C) 1996-2008 by Project Vogue.
// Written by Yoshifumi "VOGUE" INOUE. (yosi@msn.com)
//
// @(#)$Id: //proj/evedit2/mainline/tinycl/rtl/tinycl_rtl_integer.cpp#2 $
//
#include "../tinycl.h"
#include "./tinycl_bignum.h"
#include "./tinycl_float.h"
namespace TinyCl
{
using namespace Internal;
enum OpTypes
{
Operands_Big_Big = 0,
Operands_Big_Fix = 1,
Operands_Fix_Big = 2,
Operands_Fix_Fix = 3,
}; // OpTypes
template<class Operation_>
class LogArith_
{
public: static Val Dispatch(Val const a, Val const b)
{
int rgfOperands = 0;
if (fixnump(a)) rgfOperands |= Operands_Fix_Big;
if (fixnump(b)) rgfOperands |= Operands_Big_Fix;
switch (rgfOperands)
{
case Operands_Fix_Fix:
{
Int const iC = Operation_::Compute(
Fixnum::Decode_(a),
Fixnum::Decode_(b) );
return MakeInt(iC);
} // Operation_Fix_Fix
case Operands_Fix_Big:
{
if (! bignump(b)) SignalTypeError(b, Qinteger);
BignumInt oA(Fixnum::Decode_(a));
const BignumImpl* pB = b->StaticCast<BignumImpl>();
return Operation_::Compute(&oA, pB);
} // Operands_Fix_Big
case Operands_Big_Fix:
{
if (! bignump(a)) SignalTypeError(a, Qinteger);
const BignumImpl* pA = a->StaticCast<BignumImpl>();
BignumInt oB(Fixnum::Decode_(b));
return Operation_::Compute(pA, &oB);
} // Operands_Fix_Big
case Operands_Big_Big:
{
if (! bignump(a)) SignalTypeError(a, Qinteger);
if (! bignump(b)) SignalTypeError(b, Qinteger);
const BignumImpl* pA = a->StaticCast<BignumImpl>();
const BignumImpl* pB = b->StaticCast<BignumImpl>();
return Operation_::Compute(pA, pB);
} // Operands_Fix_Big
default:
CAN_NOT_HAPPEN();
} // switch operands
} // Dispatch
}; // LogArith_
#define defun_logarith(mp_name, mp_Name, mp_op2, mp_op) \
class Op ## mp_Name \
{ \
public: static Int Compute(Int const a, Int const b) \
{ return mp_op (a mp_op2 b); } \
\
public: static Val Compute( \
const BignumImpl* const pA, \
const BignumImpl* const pB ) \
{ return BignumImpl::mp_Name (pA, pB); } \
}; \
defun(mp_name, (Val const a, Val const b)) \
{ return LogArith_<Op ## mp_Name>::Dispatch(a, b); }
// [A]
defun(CommonLisp::ash, (Val x, Val n))
{
if (fixnump(n))
{
Int iN = Fixnum::Decode_(n);
if (fixnump(x))
{
Int iX = Fixnum::Decode_(x);
if (iN > 0)
{
BignumInt oX(iX);
return ash(oX, n);
}
if (iN < 0)
{
return Fixnum::Encode(iX >> -iN);
}
return x;
} // if fixnum
if (bignump(x))
{
const BignumImpl* const pX = x->StaticCast<BignumImpl>();
if (iN > 0)
{
return pX->ShiftLeft(static_cast<uint>(iN));
}
if (iN < 0)
{
return pX->ShiftRight(static_cast<uint>(-iN));
}
return x;
} // if bignum
} // if n is fixum
if (bignump(n))
{
if (fixnump(x) || bignump(x))
{
error("Too larget shift count ~D.", n);
}
SignalTypeError(n, Qinteger);
}
SignalTypeError(x, Qinteger);
} // ash
// [C]
/// <summary>
/// Coerces bignum to float32. This function is used for implementing
/// function float.
/// </summary>
/// <seealso name="coerceSbignumSfloat64"/>
defun(coerceSbignumSfloat32, (Val n))
{
if (BignumImpl* p = n->DynamicCast<BignumImpl>())
{
return Float32Impl::Make(p->ToFloat32());
}
SignalTypeError(n, Qbignum);
} // coerceSbignumSfloat32
/// <summary>
/// Coerces bignum to float64. This function is used for implementing
/// function float.
/// </summary>
/// <seealso name="coerceSbignumSfloat32"/>
defun(coerceSbignumSfloat64, (Val n))
{
if (BignumImpl* p = n->DynamicCast<BignumImpl>())
{
return Float64Impl::Make(p->ToFloat64());
}
SignalTypeError(n, Qbignum);
} // coerceSbignumSfloat64
// [G]
defun(gcdS2, (Val a, Val b))
{
if (fixnump(a))
{
Int iA = Fixnum::Decode_(a);
if (iA < 0)
{
BignumInt oA(-iA);
return gcdS2(oA, b);
}
}
else if (bignump(a))
{
if (a->StaticCast<BignumImpl>()->IsMinus())
{
a = sub(zero, a);
}
}
else
{
SignalTypeError(a, Qinteger);
}
if (fixnump(b))
{
Int iB = Fixnum::Decode_(b);
if (iB < 0)
{
BignumInt oB(-iB);
return gcdS2(a, oB);
}
}
else if (bignump(b))
{
if (b->StaticCast<BignumImpl>()->IsMinus())
{
b = sub(zero, b);
}
}
else
{
SignalTypeError(b, Qinteger);
}
for (;;)
{
int rgfOperands = 0;
if (fixnump(a)) rgfOperands |= Operands_Fix_Big;
if (fixnump(b)) rgfOperands |= Operands_Big_Fix;
switch (rgfOperands)
{
case Operands_Fix_Fix:
{
Int m = Fixnum::Decode_(a);
Int n = Fixnum::Decode_(b);
while (0 != n)
{
Int temp = m;
m = n;
n = temp % n;
} // while
return Fixnum::Encode(m);
} // fixnum fixnum
case Operands_Fix_Big:
swap(a, b);
// FALLTHROUGH
case Operands_Big_Fix:
if (zero == b)
{
return a;
}
// FALLTHROUGH
case Operands_Big_Big:
{
Val temp = a;
a = b;
b = rem(temp, b);
break;
} // bignum bignum
default:
CAN_NOT_HAPPEN();
} // switch type
} // for
} // gcdS2
// [L]
defun_logarith(logandS2, Logand, &, +)
defun_logarith(logeqvS2, Logeqv, ^, ~)
defun_logarith(logiorS2, Logior, |, +)
defun_logarith(logxorS2, Logxor, ^, +)
} // TinyCl
| [
"eval1749@gmail.com"
] | eval1749@gmail.com |
bffd605e2d1af7f38cb87ce33b18eadd549f6e6b | 1d79cb04a252bfbebcb12a05f50640caa5d49c5d | /PiTwins/private/VideoPublisher.cpp | c72a8395f9fcf863e17f0749bde93a59cc57642a | [
"Apache-2.0"
] | permissive | kkroid/PiTwins | cfcdd1a3e80b22b7164aa0009e070ae6060066a3 | 26abb35cd8b41717e75d47e097a8f7f60fa06f37 | refs/heads/master | 2023-07-05T11:20:36.398683 | 2021-08-07T14:29:18 | 2021-08-07T14:40:44 | 363,006,265 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,110 | cpp | //
// Created by Will Zhang on 2021/1/10.
//
#include "VideoPublisher.h"
using namespace std;
void VideoPublisher::detect(Mat &matFrame, vector<Rect> &rectFaces) {
Mat grayImg, resizedMat;
cvtColor(matFrame, grayImg, COLOR_BGR2GRAY);
int scale = 2;
resize(grayImg, resizedMat, Size(grayImg.cols / scale, grayImg.rows / scale));
cvDetector.detect(resizedMat, &rectFaces);
// ๅฎฝ้ซๅ็ผฉๅฐไบ2ๅ๏ผๆฃๆต็ปๆ้่ฆ็ธๅบ็ๆพๅคง
for (auto rect : rectFaces) {
rect.x = rect.x * scale;
rect.y = rect.y * scale;
rect.width = rect.width * scale;
rect.height = rect.height * scale;
// draw face rect
rectangle(matFrame, rect, Scalar(255, 0, 0), 1);
}
grayImg.release();
resizedMat.release();
}
Frame *VideoPublisher::compressFrameData(Mat &matFrame) {
vector<uchar> buff;
// imencode(".webp", matFrame, buff, params);
imencode(".jpg", matFrame, buff, params);
auto *data = new uchar[buff.size()];
copy(buff.begin(), buff.end(), data);
return new Frame(data, sizeof(uchar) * buff.size());
}
| [
"will.zhang@cloudminds.com"
] | will.zhang@cloudminds.com |
7703363a9bdec8cddceac3fcab5428ec5502cb56 | af0ecafb5428bd556d49575da2a72f6f80d3d14b | /CodeJamCrawler/dataset/14_12019_55.cpp | 4ba45343f12ff624d445cc6a5c1cd05e520db713 | [] | no_license | gbrlas/AVSP | 0a2a08be5661c1b4a2238e875b6cdc88b4ee0997 | e259090bf282694676b2568023745f9ffb6d73fd | refs/heads/master | 2021-06-16T22:25:41.585830 | 2017-06-09T06:32:01 | 2017-06-09T06:32:01 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,037 | cpp | import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Scanner;
public class Main {
public static Scanner in;
public static PrintWriter out;
public static void main(String[] args) throws FileNotFoundException {
boolean sample = false;
String input = "D-large.in";
String output = "D-large-output.txt";
if(sample){
input = "sample.in";
output = "sample.out";
}
in = new Scanner(new File(input));
out = new PrintWriter(new File(output));
int t = in.nextInt();
for(int c = 1; c <= t; c++){
solve(c);
}
in.close();
out.close();
}
public static void solve(int t){
int n = in.nextInt();
ArrayList<Double> naomi = new ArrayList<Double>();
ArrayList<Double> ken = new ArrayList<Double>();
for(int i = 0; i < n; i++){
naomi.add(in.nextDouble());
}
for(int i = 0; i < n; i++){
ken.add(in.nextDouble());
}
Collections.sort(naomi);
Collections.sort(ken);
int dans = deceitfulWar((ArrayList<Double>)naomi.clone(), (ArrayList<Double>)ken.clone());
int wans = war(naomi, ken);
System.out.printf("Case #%d: %d %d\n",t, dans, wans );
out.printf("Case #%d: %d %d\n",t, dans, wans );
}
public static int war(ArrayList<Double> naomi, ArrayList<Double> ken){
int wins = 0;
for(int i = 0; i < naomi.size(); i++){
Double n = naomi.get(i);
boolean kenWon = false;
for(int j = 0; j < ken.size() && !kenWon; j++){
Double k = ken.get(j);
if(k > n){
kenWon = true;
ken.remove(j);
}
}
if(!kenWon){
wins++;
ken.remove(0);
}
}
return wins;
}
public static int deceitfulWar(ArrayList<Double> naomi, ArrayList<Double> ken){
int wins = 0;
for(int i = 0; i < naomi.size(); i++){
Double n = naomi.get(i);
if(n > ken.get(0)){
wins++;
ken.remove(0);
}
else{
ken.remove(ken.size() -1 );
}
}
return wins;
}
}
| [
"nikola.mrzljak@fer.hr"
] | nikola.mrzljak@fer.hr |
253ed89771f6d2a24abdd23966f67b44a9f38e41 | 433a307109c52de00e1887e425b782f0aba25efe | /hw02-03/Logger.h | 86a855fcf0c5b43cb791b1de34f6c7f82ce0780c | [] | no_license | YeslieSnayder/pss | 7fc9d19ede51f5077cf9c1b66d2fd122e2e0252a | fcacab1b467c00d1d576996655f8d61540d9a418 | refs/heads/master | 2023-04-13T01:44:10.303830 | 2021-04-26T19:25:41 | 2021-04-26T19:25:41 | 334,693,118 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 568 | h | //
// Created by Andrey Kuzmickiy group BS20-03.
//
#ifndef PSS_LOGGER_H
#define PSS_LOGGER_H
#include <string>
#include <iostream>
enum Type {
INFO,
WARNING,
ERROR
};
static void log(const std::string& msg) {
std::cout << msg << std::endl;
}
static void log(Type type, const std::string& msg) {
std::string head;
if (type == INFO)
head = "INFO: ";
else if (type == WARNING)
head = "WARNING: ";
else if (type == ERROR)
head = "ERROR: ";
std::cout << head << msg << std::endl;
}
#endif //PSS_LOGGER_H | [
"a.kuzmickiy@innopolis.university"
] | a.kuzmickiy@innopolis.university |
1faedfe989ebf8f38c6701531640e640594cefa4 | b74575bb1f39ca20d8649b9f6286b5a6e875bd81 | /NetL/TimerQueue.h | 310838649d3dc3ecdc784aa76efd4b057f4c5b5a | [] | no_license | budongsi/NetL | 9a7cfc67e48a0d3ff0d74446a97956d2500ce410 | a2a094c80df89a12f9fcdee20374c70cd5888158 | refs/heads/master | 2023-02-25T11:40:23.352653 | 2021-01-29T11:27:24 | 2021-01-29T11:27:24 | 332,612,528 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,034 | h | // Copyright 2010, Shuo Chen. All rights reserved.
// http://code.google.com/p/muduo/
//
// Use of this source code is governed by a BSD-style license
// that can be found in the License file.
// Author: Shuo Chen (chenshuo at chenshuo dot com)
//
// This is an internal header file, you should not include this.
#ifndef MUDUO_NET_TIMERQUEUE_H
#define MUDUO_NET_TIMERQUEUE_H
#include <set>
#include <vector>
//#include "Mutex.h"
#include "Timestamp.h"
#include "Callbacks.h"
#include "Channel.h"
class EventLoop;
class Timer;
class TimerId;
///
/// A best efforts timer queue.
/// No guarantee that the callback will be on time.
///
class TimerQueue : boost::noncopyable
{
public:
explicit TimerQueue(EventLoop* loop);
~TimerQueue();
///
/// Schedules the callback to be run at given time,
/// repeats if @c interval > 0.0.
///
/// Must be thread safe. Usually be called from other threads.
TimerId addTimer(TimerCallback cb,
Timestamp when,
double interval);
void cancel(TimerId timerId);
private:
// FIXME: use unique_ptr<Timer> instead of raw pointers.
// This requires heterogeneous comparison lookup (N3465) from C++14
// so that we can find an T* in a set<unique_ptr<T>>.
typedef std::pair<Timestamp, Timer*> Entry;
typedef std::set<Entry> TimerList;
typedef std::pair<Timer*, int64_t> ActiveTimer;
typedef std::set<ActiveTimer> ActiveTimerSet;
void addTimerInLoop(Timer* timer);
void cancelInLoop(TimerId timerId);
// called when timerfd alarms
void handleRead();
// move out all expired timers
std::vector<Entry> getExpired(Timestamp now);
void reset(const std::vector<Entry>& expired, Timestamp now);
bool insert(Timer* timer);
EventLoop* loop_;
const int timerfd_;
Channel timerfdChannel_;
// Timer list sorted by expiration
TimerList timers_;
// for cancel()
ActiveTimerSet activeTimers_;
bool callingExpiredTimers_; /* atomic */
ActiveTimerSet cancelingTimers_;
};
#endif // MUDUO_NET_TIMERQUEUE_H
| [
"budongsi@users.noreply.github.com"
] | budongsi@users.noreply.github.com |
5a8aeda53fe231f324df4ddb18ad9ead46db8ef5 | f5d42d904bfd726127e6fb6a0f55b8a2dafba821 | /arbol.cpp | fb4d10be35009e0ca8f6db5f421b3f989501b9e6 | [] | no_license | H4ck-mex/Visual303 | b628d54f0532ca5be2c5a3fe34c1d6cb0f018f44 | 4ffb4e64a469d44c010383f340f10c999bbca7b8 | refs/heads/master | 2022-11-19T14:49:33.829234 | 2018-06-12T15:38:47 | 2018-06-12T15:38:47 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,969 | cpp | #include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include <conio.h>
using namespace std;
struct Nodo{
int dat;
Nodo *der;
Nodo *izq;
Nodo *pa;
};
Nodo *crearNodo(int);
void insNodo(Nodo *&,int,Nodo *);
Nodo *ar = NULL;
void mos(Nodo *,int);
bool busq(Nodo*,int);
void preO(Nodo *);
void inO(Nodo *);
void posO(Nodo *);
void elim(Nodo *,int);
void elimNodo(Nodo*);
Nodo* min(Nodo *);
void rempl(Nodo*, Nodo *);
void destNodo(Nodo *);
int main(){
int dat, opc,cont=0;
while (opc!=8){
printf("********************\n\n");
printf("* MENU *\n\n");
printf("********************\n\n");
printf(" Seleccione una opcion:\n\n 1) Insertar Nodo\n 2) Mostrar el Arbol\n 3) buscar un dato\n 4)recorrer en preorden\n 5)recorrer en inorden\n 6)recorrer en postorden\n 7)eliminar Nodo \n 8) Salir\n");
scanf("%i",&opc);
switch (opc){
case 1:
cout<<"ingrese un numero: ";
cin>>dat;
insNodo(ar,dat,NULL);
system("pause");
printf("\n");
break;
case 2:
cout<<"mostrando arbol"<<endl;
mos(ar,cont);
printf("\n");
system("pause");
break;
case 3:
cout<<"elija un num para buscar: ";
cin>>dat;
if(busq(ar,dat)==true){
cout<<"\nel"<<dat<<"ha sido encontrado en el arbol\n";
}
else{
cout<<"el elemento no se encontro\n";
}
system("pause");
break;
case 4:
cout<<"recorrido preorden: ";
preO(ar);
cout<<"\n";
system("pause");
break;
case 5:
cout<<"recorrido inorden: \n";
inO(ar);
system("pause");
break;
case 6:
cout<<"recorrido en postorden: \n";
posO(ar);
system("pause");
case 7:
cout<<"elija que nodo eliminar: \n";
cin>>dat;
elim(ar,dat);
system("pause");
break;
}
system("cls");
}
return 0;
}
Nodo *crearNodo(int n,Nodo *pa){
Nodo *novonodo = new Nodo();
novonodo->dat = n;
novonodo->der = NULL;
novonodo->izq = NULL;
novonodo->pa =pa;
return novonodo;
}
void mos(Nodo *ar, int cont){
if(ar == NULL){
return;
}
else{
mos(ar->der,cont+1);
for(int x=0; x<cont; x++){
printf(" ");
}
cout<<ar->dat<<endl;
mos(ar->izq,cont+1);
}
}
void insNodo(Nodo *&ar, int n,Nodo *pa){
if(ar == NULL){
Nodo *novonodo = crearNodo(n,pa);
ar = novonodo;
}else{
int valRa = ar->dat;
if(n == valRa){
cout<<"Este numero ya existe"<<endl;
}else if(n<valRa){
insNodo(ar->izq,n,ar);
}else{
insNodo(ar->der,n,ar);
}
}
}
bool busq(Nodo*ar, int x){
if(ar == NULL){
return false;
}
else if( ar->dat ==x){
return true;
}
else if(x<ar ->dat){
return busq(ar ->izq,x);
}
else{
return busq(ar->der,x);
}
}
void preO(Nodo*ar){
if(ar==NULL){
return;
}
else{
cout<<ar->dat<<" - ";
preO(ar->izq);
preO(ar->der);
}
}
void inO(Nodo*ar){
if(ar== NULL){
return;
}
else{
inO(ar->izq);
cout<<ar->dat<<"-";
inO(ar->der);
}
}
void posO(Nodo *ar){
if(ar ==NULL){
return;
}
else{
posO(ar->izq);
posO(ar->der);
cout<<ar->dat<<"-";
}
}
void elim(Nodo * ar, int x){
if(ar == NULL){
return;
}
else if(x <ar ->dat){
elim(ar->izq,x);
}
else if(x>ar->dat){
elim(ar->der,x);
}
else{
elimNodo(ar);
}
}
Nodo *min(Nodo *ar){
if(ar == NULL){
return NULL;
}
if(ar->izq){
return min(ar->izq);
}
else{
return ar;
}
}
void elimNodo(Nodo*nodoelim){
if(nodoelim->izq && nodoelim->der){
Nodo *menor =min(nodoelim->der);
nodoelim->dat=menor->dat;
elimNodo(menor);
}
else if(nodoelim->izq){
rempl(nodoelim,nodoelim->izq);
destNodo(nodoelim);
}
else if(nodoelim->der){
rempl(nodoelim,nodoelim->der);
destNodo(nodoelim);
}
else{
rempl(nodoelim,NULL);
destNodo(nodoelim);
}
}
void rempl(Nodo *ar, Nodo *novonodo ){
if(ar->pa){
if(ar->dat == ar ->pa->izq->dat){
ar->pa->izq =novonodo;
}
else if(ar ->dat ==ar ->pa->der->dat){
ar->pa->der =novonodo;
}
}
if(novonodo){
}
}
void destNodo(Nodo *nodo){
nodo->izq=NULL;
nodo->der=NULL;
delete nodo;
}
| [
"fzm89502@gmail.com"
] | fzm89502@gmail.com |
7c45bfe5581aff6c05c73f01dad28dac21b399f9 | fa9fb33d857538bd27d811a5880f044a55205a59 | /10363.cpp | 7a848d742b66fc0bbc4cf8f380f6cd5f88b5b32e | [] | no_license | Mukit09/UVA_Solution | 15b7aa8c60a9aa59a7e11a8a0163bcf437917661 | b2659637fe9ecb1cdbc164f0d1172e86f71a72d7 | refs/heads/master | 2020-12-25T17:29:17.655229 | 2020-03-18T03:56:34 | 2020-03-18T03:56:34 | 28,819,638 | 2 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 1,507 | cpp | #include<stdio.h>
#include<string.h>
int main()
{
long i,j,t,flagx,flago,x,o,d;
char ch[5][5];
scanf("%ld",&t);
getchar();
while(t--)
{
for(i=0;i<3;i++)
scanf("%s",ch[i]);
flagx=flago=x=o=0;
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
if(ch[i][j]=='X')
x++;
else if(ch[i][j]=='O')
o++;
}
}
if(ch[0][0]=='X'&&ch[0][1]=='X'&&ch[0][2]=='X')
flagx=1;
if(ch[0][0]=='O'&&ch[0][1]=='O'&&ch[0][2]=='O')
flago=1;
if(ch[0][0]=='X'&&ch[1][0]=='X'&&ch[2][0]=='X')
flagx=1;
if(ch[0][0]=='O'&&ch[1][0]=='O'&&ch[2][0]=='O')
flago=1;
if(ch[2][0]=='X'&&ch[2][1]=='X'&&ch[2][2]=='X')
flagx=1;
if(ch[2][0]=='O'&&ch[2][1]=='O'&&ch[2][2]=='O')
flago=1;
if(ch[0][2]=='X'&&ch[1][2]=='X'&&ch[2][2]=='X')
flagx=1;
if(ch[0][2]=='O'&&ch[1][2]=='O'&&ch[2][2]=='O')
flago=1;
if(ch[0][0]=='X'&&ch[1][1]=='X'&&ch[2][2]=='X')
flagx=1;
if(ch[0][0]=='O'&&ch[1][1]=='O'&&ch[2][2]=='O')
flago=1;
if(ch[0][2]=='X'&&ch[1][1]=='X'&&ch[2][0]=='X')
flagx=1;
if(ch[0][2]=='O'&&ch[1][1]=='O'&&ch[2][0]=='O')
flago=1;
if(ch[0][1]=='X'&&ch[1][1]=='X'&&ch[2][1]=='X')
flagx=1;
if(ch[0][1]=='O'&&ch[1][1]=='O'&&ch[2][1]=='O')
flago=1;
if(ch[1][0]=='X'&&ch[1][1]=='X'&&ch[1][2]=='X')
flagx=1;
if(ch[1][0]=='O'&&ch[1][1]=='O'&&ch[1][2]=='O')
flago=1;
d=x-o;
if(d<0)
d=-d;
if((flagx==1&&flago==1)||(flago==1&&flagx==0&&d>0)||(flago==0&&flagx==1&&d==0)||d>1||o>x)
printf("no\n");
else
printf("yes\n");
}
return 0;
} | [
"mukitmkbs25@yahoo.com"
] | mukitmkbs25@yahoo.com |
32819c718bb771f1d1f7bb0a6ffc47f3e6f3ca44 | 87ef03375ec4a32b7defdbdb1fbd1ed8dbb4dcbd | /Hcv/CircleContourOfPix.cpp | 969e525036e58d147a71a4cdd970be087509cede | [] | no_license | Haytham-Magdi/CppLib | 192fb2008907c3d0ae2bb34bb8c066c1d86a4c6f | c8a1ba6bca656574196ba19a75c1cbdc4b829b7c | refs/heads/master | 2020-09-20T10:54:57.022052 | 2017-01-23T05:27:52 | 2017-01-23T05:27:52 | 66,259,819 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 9,972 | cpp | #include <Lib\Cpp\Common\commonLib.h>
#include <Lib\Hcv\CvIncludes.h>
#include <Lib\Hcv\Types.h>
#include <Lib\Hcv\error.h>
#include <vector>
#include <Lib\Hcv\Channel.h>
#include <Lib\Hcv\Image.h>
#include <Lib\Hcv\funcs1.h>
#include <Lib\Hcv\CircleContourOfPix.h>
namespace Hcv
{
using namespace Hcpl;
//using namespace Hcpl::Math;
CircleContourOfPix::CircleContourOfPix( F32ImageRef a_srcImg, int a_radius )
{
Debug::Assert( 1 == a_srcImg->GetNofChannels() );
m_srcImg = a_srcImg;
m_radius = a_radius;
m_goodDirArr.SetSize(6);
m_dirShowMap.SetSize(4);
m_pntArr.SetCapacity( a_radius * 15 );
{
CircleContPathRef cp1 = new CircleContPath( 0, 180, a_radius );
do
{
F32Point pnt1 = cp1->GetCurrent();
m_pntArr.PushBack( pnt1 );
}while( cp1->MoveNext() );
}
//m_valArr.SetCapacity( a_radius * 15 );
m_valArr.SetSize( m_pntArr.GetSize() * 2 );
m_valArr2.SetSize( m_valArr.GetSize() );
m_goodArr.SetSize( m_valArr.GetSize() );
{
int nAprSiz = ( 3 * m_valArr.GetSize()) / 16;
m_avgFlt1 = LinearAvgFilter1D::Create( nAprSiz );
}
InitDirArr();
}
void CircleContourOfPix::InitDirArr()
{
const int nSize = m_valArr.GetSize();
m_dirMap1.SetSize( nSize );
m_dirMap2.SetSize( nSize );
for( int i=0; i < nSize; i++ )
{
m_dirMap1[ i ] = 5;
m_dirMap2[ i ] = 5;
}
//int nSize24 = m_valArr2.GetSize() / 24;
int nSize_24 = nSize / 32;
int nSize_4 = nSize / 4;
const int nSize_8 = nSize_4 / 2;
CircIndex ci1( nSize );
for( int i=0, m=0; i < 4; i++, m += nSize_8 )
{
//int nBgn = m - 2 * nSize_24;
//int nEnd = m + 2 * nSize_24;
int nBgn = m;
int nEnd = m;
for( int j = nBgn; j <= nEnd; j++ )
{
{
const int k = ci1.Calc( j );
if( 5 == m_dirMap1[ k ] )
m_dirMap1[ k ] = i;
m_dirMap2[ k ] = i;
}
{
const int p = ci1.Calc( j + nSize / 2 );
if( 5 == m_dirMap1[ p ] )
m_dirMap1[ p ] = i;
m_dirMap2[ p ] = i;
}
}
}
for( int i=0; i < nSize; i++ )
{
if( 5 == m_dirMap1[ i ] )
i = i;
if( 5 == m_dirMap2[ i ] )
i = i;
}
for( int i=0; i < 4; i++ )
{
const int k = ci1.Calc( i * nSize_8 );
m_dirShowMap[ i ] = k;
}
}
void CircleContourOfPix::PreparePix( int a_x, int a_y )
{
m_x = a_x;
m_y = a_y;
for( int i=0; i < m_goodDirArr.GetSize(); i++ )
m_goodDirArr[ i ] = false;
m_midVal = *m_srcImg->GetPixAt( m_x, m_y );
for( int i=0; i < m_pntArr.GetSize(); i++ )
{
F32Point pntSrcMid( a_x, a_y );
F32Point & pntI = m_pntArr[ i ];
float valI;
{
F32Point pntSrcI = pntSrcMid;
pntSrcI.IncBy( pntI );
valI = *m_srcImg->GetPixAt( pntSrcI.x, pntSrcI.y );
}
F32Point pntJ = pntI;
pntJ.MultSelfBy( -1 );
float valJ;
{
F32Point pntSrcJ = pntSrcMid;
pntSrcJ.IncBy( pntJ );
valJ = *m_srcImg->GetPixAt( pntSrcJ.x, pntSrcJ.y );
}
m_valArr[ i ] = valI;
m_valArr[ i + m_pntArr.GetSize() ] = valJ;
//if( m_midVal < valI || m_midVal < valJ )
{
//valI = 0;
//valJ = 0;
}
/*
{
F32Point & pnt1 = pntI;
F32Point pnt2 = pnt1;
pnt2.IncBy( orgPnt );
//float * pPix = img1->GetPixAt( pnt2.x, pnt2.y );
//*pPix = valI;
}
{
F32Point & pnt1 = pntJ;
F32Point pnt2 = pnt1;
pnt2.IncBy( orgPnt );
//float * pPix = img1->GetPixAt( pnt2.x, pnt2.y );
//*pPix = valJ;
}
*/
}
for( int i=0; i < m_goodArr.GetSize(); i++ )
m_goodArr[i] = false;
PrepareValArr2( );
m_avgFlt1->ResetInput();
}
void CircleContourOfPix::ShowResult()
{
{
for( int i=0; i < m_goodArr.GetSize(); i++ )
m_goodArr[ i ] = false;
//const int nSize_8 = m_goodArr.GetSize() / 8;
//for( int i=0; i < m_goodDirArr.GetSize(); i++ )
for( int i=0; i < 4; i++ )
//for( int i=0; i < m_goodDirArr.GetSize(); i += nSize_8 )
{
if( m_goodDirArr[ i ] )
m_goodArr[ m_dirShowMap[ i ] ] = true;
}
}
//CvSize siz1 = cvSize( 400, 400 );
//CvSize siz1 = cvSize( 40, 40 );
CvSize siz1 = cvSize( m_radius * 4, m_radius * 4 );
F32ImageRef img1 = F32Image::Create( siz1, 1 );
img1->SetAll(0);
F32Point orgPnt( siz1.width / 2, siz1.height / 2 );
*img1->GetPixAt( orgPnt.x, orgPnt.y ) = 255;
//*img1->GetPixAt( orgPnt.x, orgPnt.y ) = m_midVal;
if( m_orderRatio > 0.333 )
*img1->GetPixAt( orgPnt.x, orgPnt.y ) = 128;
/*
FixedVector< F32Point > pntArr(300);
do
{
F32Point pnt1 = cp1->GetCurrent();
pntArr.PushBack( pnt1 );
}while( cp1->MoveNext() );
*/
F32Point pntSrcMid( m_x, m_y );
//FixedVector< float > valArr;
//valArr.SetSize( pntArr.GetSize() * 2 );
for( int i=0; i < m_pntArr.GetSize(); i++ )
{
int j = i + m_pntArr.GetSize();
F32Point & pntI = m_pntArr[ i ];
float valI;
{
F32Point pntSrcI = pntSrcMid;
pntSrcI.IncBy( pntI );
//valI = *m_srcImg->GetPixAt( pntSrcI.x, pntSrcI.y );
valI = 255;
}
F32Point pntJ = pntI;
pntJ.MultSelfBy( -1 );
float valJ;
{
F32Point pntSrcJ = pntSrcMid;
pntSrcJ.IncBy( pntJ );
//valJ = *m_srcImg->GetPixAt( pntSrcJ.x, pntSrcJ.y );
valJ = 255;
}
//valArr[ i ] = valI;
//valArr[ i + m_pntArr.GetSize() ] = valJ;
//if( m_midVal < valI || m_midVal < valJ )
{
//valI = 0;
//valJ = 0;
}
if( ! m_goodArr[i] )
{
valI = 0;
if( m_goodArr[j] )
valJ = 128;
}
if( ! m_goodArr[j] )
{
if( m_goodArr[i] )
valI = 128;
valJ = 0;
}
{
F32Point & pnt1 = pntI;
F32Point pnt2 = pnt1;
pnt2.IncBy( orgPnt );
float * pPix = img1->GetPixAt( pnt2.x, pnt2.y );
*pPix = valI;
}
{
F32Point & pnt1 = pntJ;
F32Point pnt2 = pnt1;
pnt2.IncBy( orgPnt );
float * pPix = img1->GetPixAt( pnt2.x, pnt2.y );
*pPix = valJ;
}
}
//ShowValArrSignal( m_valArr, "CircSig" );
ShowValArrSignal( m_valArr2, "CircSig2" );
F32ImageRef img2 = GenUpSampledImage( img1, 10 );
ShowImage( img2, "CircleContPath" );
}
void CircleContourOfPix::ShowValArrSignal( FixedVector< float > & a_valArr, char * a_sWndName )
{
const int nScaleW = 800 / a_valArr.GetSize() + 1;
Signal1DViewer sv1;
int i;
{
Signal1DBuilder sb1(1000);
for( int j=0; j < a_valArr.GetSize(); j++ )
{
for( int k=0; k < nScaleW; k++ )
sb1.AddValue( m_midVal );
}
sv1.AddSignal( sb1.GetResult(), u8ColorVal( 0, 170, 0 ) );
}
//bool bDone;
U8ColorVal colorArr[ 4 ];
{
int nCnt = 0;
colorArr[ nCnt++ ] = u8ColorVal( 0, 0, 255 );
colorArr[ nCnt++ ] = u8ColorVal( 200, 0, 0 );
colorArr[ nCnt++ ] = u8ColorVal( 200, 0, 200 );
colorArr[ nCnt++ ] = u8ColorVal( 255, 255, 255 );
}
for( int i=0,m=0; m < 8; m++ )
{
{
Signal1DBuilder sb1( 1000, i * nScaleW );
int nLim = i + a_valArr.GetSize() / 8;
if( nLim > a_valArr.GetSize() )
nLim = a_valArr.GetSize();
//bDone = false;
for( ; i < nLim; i++ )
{
for( int k=0; k < nScaleW; k++ )
{
sb1.AddValue( a_valArr[i] );
//bDone = true;
}
}
sv1.AddSignal( sb1.GetResult(), colorArr[ m % 4 ] );
/*
if( m < 2 )
sv1.AddSignal( sb1.GetResult(), u8ColorVal( 0, 0, 255 ) );
else
sv1.AddSignal( sb1.GetResult(), u8ColorVal( 200, 0, 200 ) );
*/
}
/*
{
Signal1DBuilder sb1( 1000, i * nScaleW );
int nLim = i + a_valArr.GetSize() / 8;
if( nLim > a_valArr.GetSize() )
nLim = a_valArr.GetSize();
//bDone = false;
for( ; i < nLim; i++ )
{
for( int k=0; k < nScaleW; k++ )
{
sb1.AddValue( a_valArr[i] );
//bDone = true;
}
}
if( m < 2 )
//sv1.AddSignal( sb1.GetResult(), u8ColorVal( 200, 0, 200 ) );
sv1.AddSignal( sb1.GetResult(), u8ColorVal( 200, 0, 0 ) );
else
sv1.AddSignal( sb1.GetResult(), u8ColorVal( 255, 255, 255 ) );
}
*/
}
ShowImage( sv1.GenDisplayImage(), a_sWndName );
//sv1
}
void CircleContourOfPix::PrepareValArr2( )
{
CircIndex ci1( m_valArr.GetSize() );
//int nAprSiz = ( 3 * m_valArr.GetSize()) / 16;
//IFilter1DRef avgFlt1 = LinearAvgFilter1D::Create( nAprSiz );
IFilter1DRef avgFlt1 = m_avgFlt1;
const int nBackShift = avgFlt1->GetBackShift();
int nCnt = 0;
const int nLim = m_valArr.GetSize() + avgFlt1->GetLength() - 1;
for( int i=0; i < nLim; i++ )
{
avgFlt1->InputVal( m_valArr[ ci1.Calc( i ) ] );
if( ! avgFlt1->HasOutput() )
continue;
float outVal = avgFlt1->CalcOutput();
m_valArr2[ ci1.Calc( i - nBackShift ) ] = outVal;
if( outVal >= m_midVal )
nCnt++;
}
m_orderRatio = (float) nCnt / m_valArr.GetSize();
const int nDist1 = m_valArr.GetSize() / 8;
const int nDist2 = m_valArr.GetSize() / 4;
for( int i=0; i < m_goodArr.GetSize(); i++ )
{
float val0 = m_valArr2[ i ];
if( val0 > m_midVal )
continue;
/*
if( val0 >= m_valArr2[ ci1.Calc( i - nDist1 ) ] )
{
if( val0 >= m_valArr2[ ci1.Calc( i - nDist2 ) ] )
continue;
}
if( val0 >= m_valArr2[ ci1.Calc( i + nDist1 ) ] )
{
if( val0 >= m_valArr2[ ci1.Calc( i + nDist2 ) ] )
continue;
}
//m_goodArr[i] = true;
*/
if( val0 > m_valArr2[ ci1.Calc( i - nDist1 ) ] ||
val0 > m_valArr2[ ci1.Calc( i + nDist1 ) ] )
{
continue;
}
if( val0 < m_valArr2[ ci1.Calc( i - nDist1 ) ] &&
val0 < m_valArr2[ ci1.Calc( i + nDist1 ) ] )
{
m_goodArr[i] = true;
continue;
}
if( val0 < m_valArr2[ ci1.Calc( i - nDist2 ) ] &&
val0 < m_valArr2[ ci1.Calc( i + nDist2 ) ] )
{
m_goodArr[i] = true;
}
}
const int nSize_2 = m_goodArr.GetSize() / 2;
for( int i=0; i < nSize_2 ; i++ )
{
int j = i + nSize_2;
int crIdxI = ci1.Calc( i );
int crIdxJ = ci1.Calc( j );
if( m_goodArr[ crIdxI ] && m_goodArr[ crIdxJ ] )
{
m_goodDirArr[ m_dirMap1[ crIdxI ] ] = true;
m_goodDirArr[ m_dirMap2[ crIdxI ] ] = true;
}
}
}
} | [
"haytham.magdi@hotmail.com"
] | haytham.magdi@hotmail.com |
8e61d3779b9cf168128b330f095d764e506b475b | 9082f4c9c50acc364b46d994c20927a44b528888 | /debug/moc_cmysqlconnect.cpp | a6dd184de2c8f5422ba79d732bbdd62fc36e453c | [] | no_license | bedinin/journal | 7e7381746680e8f92bce9880ccaad85f975c5f5a | 487948194f2a9bd606301fd0f6843744a821f802 | refs/heads/master | 2021-01-15T17:45:42.885539 | 2013-04-23T11:01:22 | 2013-04-23T11:01:22 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,102 | cpp | /****************************************************************************
** Meta object code from reading C++ file 'cmysqlconnect.h'
**
** Created: Sat 15. Dec 16:12:55 2012
** by: The Qt Meta Object Compiler version 62 (Qt 4.7.3)
**
** WARNING! All changes made in this file will be lost!
*****************************************************************************/
#include "../cmysqlconnect.h"
#if !defined(Q_MOC_OUTPUT_REVISION)
#error "The header file 'cmysqlconnect.h' doesn't include <QObject>."
#elif Q_MOC_OUTPUT_REVISION != 62
#error "This file was generated using the moc from 4.7.3. It"
#error "cannot be used with the include files from this version of Qt."
#error "(The moc has changed too much.)"
#endif
QT_BEGIN_MOC_NAMESPACE
static const uint qt_meta_data_CMysqlConnect[] = {
// content:
5, // revision
0, // classname
0, 0, // classinfo
0, 0, // methods
0, 0, // properties
0, 0, // enums/sets
0, 0, // constructors
0, // flags
0, // signalCount
0 // eod
};
static const char qt_meta_stringdata_CMysqlConnect[] = {
"CMysqlConnect\0"
};
const QMetaObject CMysqlConnect::staticMetaObject = {
{ &QObject::staticMetaObject, qt_meta_stringdata_CMysqlConnect,
qt_meta_data_CMysqlConnect, 0 }
};
#ifdef Q_NO_DATA_RELOCATION
const QMetaObject &CMysqlConnect::getStaticMetaObject() { return staticMetaObject; }
#endif //Q_NO_DATA_RELOCATION
const QMetaObject *CMysqlConnect::metaObject() const
{
return QObject::d_ptr->metaObject ? QObject::d_ptr->metaObject : &staticMetaObject;
}
void *CMysqlConnect::qt_metacast(const char *_clname)
{
if (!_clname) return 0;
if (!strcmp(_clname, qt_meta_stringdata_CMysqlConnect))
return static_cast<void*>(const_cast< CMysqlConnect*>(this));
return QObject::qt_metacast(_clname);
}
int CMysqlConnect::qt_metacall(QMetaObject::Call _c, int _id, void **_a)
{
_id = QObject::qt_metacall(_c, _id, _a);
if (_id < 0)
return _id;
return _id;
}
QT_END_MOC_NAMESPACE
| [
"bedja87@mail.ru"
] | bedja87@mail.ru |
63a4174e7fddb74a71bce5e064ce2aff0bbd5873 | 4d317369bd7de599e0364e9097e50f381845e22c | /2021/Div 2/724/Programs/Omkar and Forest.cpp | 4d8483cfcf02ecad47fd35d07df0442bc2d8b5be | [] | no_license | MathProgrammer/CodeForces | 4865f0bad799c674ff9e6fde9a008b988af2aed0 | e3483c1ac4a7c81662f6a0bc8af20be69e0c0a98 | refs/heads/master | 2023-04-07T11:27:31.766011 | 2023-04-01T06:29:19 | 2023-04-01T06:29:19 | 84,833,335 | 256 | 114 | null | 2021-10-02T21:14:47 | 2017-03-13T14:02:57 | C++ | UTF-8 | C++ | false | false | 1,116 | cpp | #include <iostream>
#include <vector>
using namespace std;
long long power_mod(long long x, long long power, long long mod)
{
long long result = 1;
while(power)
{
if(power%2 == 1)
result = (result*x)%mod;
x = (x*x)%mod;
power = power >> 1;
}
return result;
}
void solve()
{
int rows, columns;
cin >> rows >> columns;
vector <string> grid(rows);
for(int i = 0; i < rows; i++)
{
cin >> grid[i];
}
const char FREE_SPACE = '#';
int free_spaces = 0;
for(int r = 0; r < rows; r++)
{
for(int c = 0; c < columns; c++)
{
free_spaces += (grid[r][c] == FREE_SPACE);
}
}
const int MOD = 1e9 + 7;
long long answer = power_mod(2, free_spaces, MOD);
if(free_spaces == rows*columns)
{
answer = (answer + MOD - 1)%MOD;
}
cout << answer << "\n";
}
int main()
{
int no_of_test_cases;
cin >> no_of_test_cases;
while(no_of_test_cases--)
solve();
return 0;
}
| [
"noreply@github.com"
] | MathProgrammer.noreply@github.com |
dbb4e511bdcf584aaf5f0c05c3c4441823703a74 | 8cb90f14f3e220f40ae7d6445144430ef6c06a6b | /ClassWeapon.cpp | b701d1685165d2badc7ebf020444627fe3fe4f43 | [] | no_license | michael-hentz/5by5-Text-RPG | f1f7e3a514f36bbfbc292a059a5dc42e1651a952 | 7232dc8bb80af1e43bdc0c8c5ba46afb94283d85 | refs/heads/master | 2022-07-21T22:19:29.023467 | 2020-05-15T23:35:09 | 2020-05-15T23:35:09 | 262,882,335 | 0 | 0 | null | 2020-05-15T23:35:11 | 2020-05-10T21:54:10 | null | UTF-8 | C++ | false | false | 156 | cpp | class weapon {
public:
weapon();
void setDamage();
void getDamage();
private:
};
weapon::weapon();
void weapon::setDamage();
void weapon::getDamage(); | [
"mthe229@uky.edu"
] | mthe229@uky.edu |
cee40cac4e44115fecf01906528b4ab4465c57cd | 1807dd1092eb33fd5fba9b899bd82db11021cf2d | /dtn/main.cpp | e4ad6b6d4537ed517ad305b6cf8e2f7eab761c9d | [] | no_license | Hansonlet/stk | 6fa36478cbb85ae46d1e88d6e9dadf2b2566bf04 | ff47d33b7209f5c486de264de67857066d2d864a | refs/heads/master | 2023-05-31T10:43:28.422985 | 2021-06-24T11:07:34 | 2021-06-24T11:07:44 | 352,234,744 | 1 | 0 | null | null | null | null | GB18030 | C++ | false | false | 8,169 | cpp | #include "load_file.h"
#include "settings.h"
void
Caculate_SendRate() {
//ๅซๆๅธฆๅฎฝๅๅงๅ
for (int i = moon_Node_Num; i < sum_Num - 1; ++i) {
SENDRATE[i] = TOTAL_BANDWIDTH;
}
int ship_connects[sum_Num];
memset(ship_connects, 0, sum_Num * sizeof(int));
//ๅ้
้ฃ่นๅ้ๅธฆๅฎฝ๏ผๅนถๅๅป็ธๅบๅซๆๅธฆๅฎฝไฝ้
for (int i = moon_Surface_Num; i < moon_Node_Num; ++i) {
SENDRATE[i] = MAX_PER_SHIP_BANDWIDTH;
if (established_to_which[i] >= moon_Surface_Num && established_to_which[i] < moon_Node_Num) {
SENDRATE[established_to_which[i]] -= MAX_PER_SHIP_BANDWIDTH * USERS_PER_SHIP;
ship_connects[established_to_which[i]]++;
}
}
//ๅ้
ๆ่กจ่็นๅ้ๅธฆๅฎฝ
for (int i = 0; i < moon_Surface_Num; ++i) {
if (established_to_which[i] == sum_Num - 1) {
SENDRATE[i] = TOTAL_BANDWIDTH;
}
else if (established_to_which[i] < moon_Node_Num) {
SENDRATE[i] = MAX_PER_SHIP_BANDWIDTH;
}
else {
SENDRATE[i] = SENDRATE[established_to_which[i]] * USERS_PER_MOON /
(established_counts[established_to_which[i]] - ship_connects[established_to_which[i]]);
if (SENDRATE[i] > MAX_PER_NODE_BANDWIDTH) {
SENDRATE[i] = MAX_PER_NODE_BANDWIDTH;
}
}
}
//ๅ้
ๅซๆๅ้ๅธฆๅฎฝ
for (int i = moon_Node_Num; i < sum_Num - 1; ++i) {
if (established_to_which[i] == sum_Num - 1) {
SENDRATE[i] = TOTAL_BANDWIDTH;
}
else if (established_to_which[i] < moon_Node_Num) {
SENDRATE[i] = SENDRATE[i] /
(established_counts[established_to_which[i]] - ship_connects[established_to_which[i]]);
}
else {
SENDRATE[i] = MAX_PER_NODE_BANDWIDTH;
}
}
}
void
Output_TempResult(const vector<float>& result_maxbuffersize) {
if ((int)NOW_TIME % 100000 == 0) {
int total_packets_realtime = (NOW_TIME - 12 * 3600) * 9;
int total_packets_unrealtime = (NOW_TIME - 12 * 3600) * 9 * 2;
if (total_packets_realtime > 63763200 / 3) { total_packets_realtime = 63763200 / 3; }
if (total_packets_unrealtime > 63763200 / 3 * 2) { total_packets_unrealtime = 63763200 / 3 * 2; }
cout << "---------------- " << (int)NOW_TIME / 100000 << "0Ws passed ----------------" << endl <<
(RECEIVED_PACKETS_REALTIME+ RECEIVED_PACKETS_UNREALTIME) << " / " << total_packets_realtime + total_packets_unrealtime << " received.( " <<
static_cast<double>(RECEIVED_PACKETS_REALTIME + RECEIVED_PACKETS_UNREALTIME) / static_cast<double>(total_packets_realtime+ total_packets_unrealtime) * 100 << "%)."
<< endl;
cout << "Max buffersize:" << endl;
for (int i = 0; i < sum_Num - 1; ++i) {
cout << i << ": " << result_maxbuffersize[i] << "\t";
if (i % 7 == 6) {
cout << endl;
}
}
cout << endl;
cout << "Average Delay: " << (TOTAL_DELAY_REALTIME + TOTAL_DELAY_UNREALTIME) / (RECEIVED_PACKETS_REALTIME + RECEIVED_PACKETS_UNREALTIME) << endl;
//file output
temp_result << "---------------- " << (int)NOW_TIME / 100000 << "0Ws passed ----------------" << endl <<
(RECEIVED_PACKETS_REALTIME + RECEIVED_PACKETS_UNREALTIME) << " / " << total_packets_realtime + total_packets_unrealtime << " received.( " <<
static_cast<double>(RECEIVED_PACKETS_REALTIME + RECEIVED_PACKETS_UNREALTIME) / static_cast<double>(total_packets_realtime + total_packets_unrealtime) * 100 << "%)."
<< endl;
temp_result << "Max buffersize:" << endl;
for (int i = 0; i < sum_Num - 1; ++i) {
temp_result << i << ": " << result_maxbuffersize[i] << "\t";
if (i % 6 == 5) {
temp_result << endl;
}
}
temp_result << endl;
temp_result << "Average Delay: " << (TOTAL_DELAY_REALTIME + TOTAL_DELAY_UNREALTIME) / (RECEIVED_PACKETS_REALTIME + RECEIVED_PACKETS_UNREALTIME) << endl;
}
}
void Output_LastResult(const vector<float>& result_maxbuffersize) {
int total_packets_realtime = (NOW_TIME - 12 * 3600) * 9;
int total_packets_unrealtime = (NOW_TIME - 12 * 3600) * 9 * 2;
if (total_packets_realtime > 63763200 / 3) { total_packets_realtime = 63763200 / 3; }
if (total_packets_unrealtime > 63763200 / 3 * 2) { total_packets_unrealtime = 63763200 / 3 * 2; }
cout << "---------------- The end ----------------" << endl <<
RECEIVED_PACKETS_REALTIME + RECEIVED_PACKETS_UNREALTIME << " / " << total_packets_realtime + total_packets_unrealtime << " received.( " <<
static_cast<double>(RECEIVED_PACKETS_REALTIME + RECEIVED_PACKETS_UNREALTIME) / static_cast<double>(total_packets_realtime + total_packets_unrealtime) * 100 << "%)."
<< endl;
cout << "Max buffersize:" << endl;
for (int i = 0; i < sum_Num - 1; ++i) {
cout << i << ": " << result_maxbuffersize[i] << "\t";
if (i % 6 == 5) {
cout << endl;
}
}
cout << endl;
cout << "Average Delay: " << (TOTAL_DELAY_REALTIME+ TOTAL_DELAY_UNREALTIME) / (RECEIVED_PACKETS_REALTIME + RECEIVED_PACKETS_UNREALTIME) << endl;
//file output
result << "---------------- The end ----------------" << endl <<
RECEIVED_PACKETS_REALTIME + RECEIVED_PACKETS_UNREALTIME << " / " << total_packets_realtime + total_packets_unrealtime << " received.( " <<
static_cast<double>(RECEIVED_PACKETS_REALTIME + RECEIVED_PACKETS_UNREALTIME) / static_cast<double>(total_packets_realtime + total_packets_unrealtime) * 100 << "%)."
<< endl;
result << "Max buffersize:" << endl;
for (int i = 0; i < sum_Num - 1; ++i) {
result << i << ": " << result_maxbuffersize[i] << "\t";
if (i % 6 == 5) {
result << endl;
}
}
result << endl;
result << "Average Delay: " << (TOTAL_DELAY_REALTIME + TOTAL_DELAY_UNREALTIME) / (RECEIVED_PACKETS_REALTIME + RECEIVED_PACKETS_UNREALTIME) << endl;
}
int main() {
cout << "-------------- Simulator Begin --------------" << endl;
cout << "Sum Nodes: " << sum_Num << " Total Simulator Time: " << SIMULATOR_TIME_INT << endl;
cout << "Bandwidth: " << TOTAL_BANDWIDTH << " Moon Buffer Size: " << MOONBUFFERSIZE << " Satellite Buffer Size: " << SATELLITEBUFFERSIZE << endl;
cout << "Store time: " << UNREALTIME_MAXDELAY << endl;
//buffer_out.setf(ios::fixed, ios::floatfield);
//buffer_out.precision(2);
packet_out.setf(ios::fixed, ios::floatfield);
packet_out.precision(2);
hops_out.setf(ios::fixed, ios::floatfield);
hops_out.precision(2);
temp_result.setf(ios::fixed, ios::floatfield);
temp_result.precision(2);
result.setf(ios::fixed, ios::floatfield);
result.precision(2);
fill(isConnected[0][0], isConnected[0][0] + SIMULATOR_TIME_INT * sum_Num * sum_Num, false);
Init_IsConnected_Hashmap();
vector<float> result_maxbuffersize;
for (int i = 0; i < sum_Num; ++i) {
established_counts[i] = 0;
established_to_which[i] = -1;
result_maxbuffersize.push_back(0);
}
for (int i = 0; i < sum_Num; ++i) {
NODE_OBJECT[i].setID(i);
//NODE_OBJECT[i].SetMaxBandwidth();
if (i < moon_Surface_Num) { NODE_OBJECT[i].setBufferSize(MOONBUFFERSIZE); }
else { NODE_OBJECT[i].setBufferSize(SATELLITEBUFFERSIZE); }
}
for (; NOW_TIME <= SIMULATOR_TIME; ++NOW_TIME) {
//ๅ้
ๅธฆๅฎฝ่ตๆบ
Caculate_SendRate();
//ๆฃๆฅ่ฟๆฅ็ถๆ
for (int i = 0; i < sum_Num - 1; ++i) {
//ๅปบ็ซ่ฟๆฅไบ ่ไธ ็ฉ็ไธไธ้ไบ,ๆญๅผto_which๏ผๅๅฐcounts
if (established_to_which[i] != -1 && (!isConnected[(int)NOW_TIME][i][established_to_which[i]])) {
NODE_OBJECT[i].Delete_Connect(established_to_which[i]);
}
}
//moon node
for (int i = 0; i < moon_Node_Num; ++i) {
NODE_OBJECT[i].GeneratePacket();
if (i == 0 || i == 1) {
NODE_OBJECT[i].ReceivePacket();
}
NODE_OBJECT[i].CheckBuffer();
NODE_OBJECT[i].SendPacket();
}
//satellite
for (int i = moon_Node_Num; i < moon_Node_Num + satellite_Node_Num; ++i) {
NODE_OBJECT[i].ReceivePacket();
NODE_OBJECT[i].CheckBuffer();
NODE_OBJECT[i].SendPacket();
}
//earth
for (int i = moon_Node_Num + satellite_Node_Num; i < moon_Node_Num + satellite_Node_Num + earth_Node_Num; ++i) {
NODE_OBJECT[i].ReceivePacket();
}
//buffer out
if (NOW_TIME > 43200 && NOW_TIME < 2404800) {
for (int i = 0; i < sum_Num - 1; ++i) {
if (result_maxbuffersize[i] < NODE_OBJECT[i].Get_BufferSizeUsed()) {
result_maxbuffersize[i] = NODE_OBJECT[i].Get_BufferSizeUsed();
}
}
}
Output_TempResult(result_maxbuffersize);
}
Output_LastResult(result_maxbuffersize);
char a;
std::cin >> a;
return 0;
}
| [
"bit_xzh@163.com"
] | bit_xzh@163.com |
34e257004bad7d2e8572a9ce7c473516a59795cb | 3bc68cf9e67e65754819694a9df2086d9569d749 | /src/qt/sendcoinsentry.cpp | 319c1ef3e176e068d6e7165f0f2f43903865c8e3 | [
"MIT"
] | permissive | white92d15b7/NLX | 72d7b7e2cb02b69563b332730ad9cc992db1428d | ba6f0c9dd317318b8bb57869d2d975ed09513de4 | refs/heads/master | 2021-06-17T10:36:42.492008 | 2019-08-22T13:08:43 | 2019-08-22T13:08:43 | 139,143,185 | 2 | 12 | MIT | 2019-06-13T22:01:11 | 2018-06-29T11:49:19 | C++ | UTF-8 | C++ | false | false | 7,435 | cpp | // Copyright (c) 2011-2014 The Bitcoin developers
// Copyright (c) 2014-2015 The Dash developers
// Copyright (c) 2015-2017 The PIVX developers
// Copyright (c) 2015-2019 The NulleX developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "sendcoinsentry.h"
#include "ui_sendcoinsentry.h"
#include "addressbookpage.h"
#include "addresstablemodel.h"
#include "guiutil.h"
#include "optionsmodel.h"
#include "walletmodel.h"
#include <QApplication>
#include <QClipboard>
SendCoinsEntry::SendCoinsEntry(QWidget* parent) : QStackedWidget(parent),
ui(new Ui::SendCoinsEntry),
model(0)
{
ui->setupUi(this);
setCurrentWidget(ui->SendCoins);
#ifdef Q_OS_MAC
ui->payToLayout->setSpacing(4);
#endif
#if QT_VERSION >= 0x040700
ui->addAsLabel->setPlaceholderText(tr("Enter a label for this address to add it to your address book"));
#endif
// normal NulleX address field
GUIUtil::setupAddressWidget(ui->payTo, this);
// just a label for displaying NulleX address(es)
ui->payTo_is->setFont(GUIUtil::bitcoinAddressFont());
// Connect signals
connect(ui->payAmount, SIGNAL(valueChanged()), this, SIGNAL(payAmountChanged()));
connect(ui->deleteButton, SIGNAL(clicked()), this, SLOT(deleteClicked()));
connect(ui->deleteButton_is, SIGNAL(clicked()), this, SLOT(deleteClicked()));
connect(ui->deleteButton_s, SIGNAL(clicked()), this, SLOT(deleteClicked()));
}
SendCoinsEntry::~SendCoinsEntry()
{
delete ui;
}
void SendCoinsEntry::on_pasteButton_clicked()
{
// Paste text from clipboard into recipient field
ui->payTo->setText(QApplication::clipboard()->text());
}
void SendCoinsEntry::on_addressBookButton_clicked()
{
if (!model)
return;
AddressBookPage dlg(AddressBookPage::ForSelection, AddressBookPage::SendingTab, this);
dlg.setModel(model->getAddressTableModel());
if (dlg.exec()) {
ui->payTo->setText(dlg.getReturnValue());
ui->payAmount->setFocus();
}
}
void SendCoinsEntry::on_payTo_textChanged(const QString& address)
{
updateLabel(address);
}
void SendCoinsEntry::setModel(WalletModel* model)
{
this->model = model;
if (model && model->getOptionsModel())
connect(model->getOptionsModel(), SIGNAL(displayUnitChanged(int)), this, SLOT(updateDisplayUnit()));
clear();
}
void SendCoinsEntry::clear()
{
// clear UI elements for normal payment
ui->payTo->clear();
ui->addAsLabel->clear();
ui->payAmount->clear();
ui->messageTextLabel->clear();
ui->messageTextLabel->hide();
ui->messageLabel->hide();
// clear UI elements for insecure payment request
ui->payTo_is->clear();
ui->memoTextLabel_is->clear();
ui->payAmount_is->clear();
// clear UI elements for secure payment request
ui->payTo_s->clear();
ui->memoTextLabel_s->clear();
ui->payAmount_s->clear();
// update the display unit, to not use the default ("BTC")
updateDisplayUnit();
}
void SendCoinsEntry::deleteClicked()
{
emit removeEntry(this);
}
bool SendCoinsEntry::validate()
{
if (!model)
return false;
// Check input validity
bool retval = true;
// Skip checks for payment request
if (recipient.paymentRequest.IsInitialized())
return retval;
if (!model->validateAddress(ui->payTo->text())) {
ui->payTo->setValid(false);
retval = false;
}
if (!ui->payAmount->validate()) {
retval = false;
}
// Sending a zero amount is invalid
if (ui->payAmount->value(0) <= 0) {
ui->payAmount->setValid(false);
retval = false;
}
// Reject dust outputs:
if (retval && GUIUtil::isDust(ui->payTo->text(), ui->payAmount->value())) {
ui->payAmount->setValid(false);
retval = false;
}
return retval;
}
SendCoinsRecipient SendCoinsEntry::getValue()
{
// Payment request
if (recipient.paymentRequest.IsInitialized())
return recipient;
// Normal payment
recipient.address = ui->payTo->text();
recipient.label = ui->addAsLabel->text();
recipient.amount = ui->payAmount->value();
recipient.message = ui->messageTextLabel->text();
return recipient;
}
QWidget* SendCoinsEntry::setupTabChain(QWidget* prev)
{
QWidget::setTabOrder(prev, ui->payTo);
QWidget::setTabOrder(ui->payTo, ui->addAsLabel);
QWidget* w = ui->payAmount->setupTabChain(ui->addAsLabel);
QWidget::setTabOrder(w, ui->addressBookButton);
QWidget::setTabOrder(ui->addressBookButton, ui->pasteButton);
QWidget::setTabOrder(ui->pasteButton, ui->deleteButton);
return ui->deleteButton;
}
void SendCoinsEntry::setValue(const SendCoinsRecipient& value)
{
recipient = value;
if (recipient.paymentRequest.IsInitialized()) // payment request
{
if (recipient.authenticatedMerchant.isEmpty()) // insecure
{
ui->payTo_is->setText(recipient.address);
ui->memoTextLabel_is->setText(recipient.message);
ui->payAmount_is->setValue(recipient.amount);
ui->payAmount_is->setReadOnly(true);
setCurrentWidget(ui->SendCoins_InsecurePaymentRequest);
} else // secure
{
ui->payTo_s->setText(recipient.authenticatedMerchant);
ui->memoTextLabel_s->setText(recipient.message);
ui->payAmount_s->setValue(recipient.amount);
ui->payAmount_s->setReadOnly(true);
setCurrentWidget(ui->SendCoins_SecurePaymentRequest);
}
} else // normal payment
{
// message
ui->messageTextLabel->setText(recipient.message);
ui->messageTextLabel->setVisible(!recipient.message.isEmpty());
ui->messageLabel->setVisible(!recipient.message.isEmpty());
ui->addAsLabel->clear();
ui->payTo->setText(recipient.address); // this may set a label from addressbook
if (!recipient.label.isEmpty()) // if a label had been set from the addressbook, dont overwrite with an empty label
ui->addAsLabel->setText(recipient.label);
ui->payAmount->setValue(recipient.amount);
}
}
void SendCoinsEntry::setAddress(const QString& address)
{
ui->payTo->setText(address);
ui->payAmount->setFocus();
}
bool SendCoinsEntry::isClear()
{
return ui->payTo->text().isEmpty() && ui->payTo_is->text().isEmpty() && ui->payTo_s->text().isEmpty();
}
void SendCoinsEntry::setFocus()
{
ui->payTo->setFocus();
}
void SendCoinsEntry::updateDisplayUnit()
{
if (model && model->getOptionsModel()) {
// Update payAmount with the current unit
ui->payAmount->setDisplayUnit(model->getOptionsModel()->getDisplayUnit());
ui->payAmount_is->setDisplayUnit(model->getOptionsModel()->getDisplayUnit());
ui->payAmount_s->setDisplayUnit(model->getOptionsModel()->getDisplayUnit());
}
}
bool SendCoinsEntry::updateLabel(const QString& address)
{
if (!model)
return false;
// Fill in label from address book, if address has an associated label
QString associatedLabel = model->getAddressTableModel()->labelForAddress(address);
if (!associatedLabel.isEmpty()) {
ui->addAsLabel->setText(associatedLabel);
return true;
}
return false;
}
| [
"partridget9@gmail.com"
] | partridget9@gmail.com |
f446aceaa428f3a761c0793b86403553391d2bf3 | 19950efb36b2dfdfdb37af60410452895a4ca627 | /Fibonacci/FibThreeNumbers/Fib3/main.cpp | 2ca0f55d050d1712b241382c21f74dc0cc9a5b5d | [] | no_license | Obrubok/Algorithms | 3067b0639fe3d4b2f8572f2e8b1a5d6a63d6e355 | 47511b09ee64c3f5f8ac892555bcee256ef32699 | refs/heads/main | 2023-03-24T10:24:09.523908 | 2021-03-20T00:03:47 | 2021-03-20T00:03:47 | 349,583,092 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 901 | cpp | #include <iostream>
using namespace std;
int Fib3(int n);
int FibLastDigit(int n);
int main()
{
int n;
cout << "ะะฒะตะดะธัะต ะฝะพะผะตั ัะธัะปะฐ ะคะธะฑะพะฝะฐััะธ: ";
cin >> n;
cout << n << " ัะธัะปะพ ะคะธะฑะพะฝะฐััะธ = " << Fib3(n) << endl;
cout << "ะะพัะปะตะดะฝัั ัะธััะฐ " << n << " ัะธัะปะฐ ะคะธะฑะพะฝะฐััะธ: " << FibLastDigit(n) << endl;
return 0;
}
int Fib3(int n)
{
if (n <= 1) {
return n;
}
int a, b, temp;
a = 0;
b = 1;
for (int i = 2; i <= n; i++) {
temp = b;
b += a;
a = temp;
temp = b - a;
}
return b;
}
int FibLastDigit(int n)
{
if (n <= 1) {
return n;
}
int a = 0, b = 1, temp = 0;
// a = 0;
// b = 1;
// temp = 0;
for (int i = 2; i <= n; i++) {
temp = b;
b = (a + b) % 10;
a = temp;
}
return b;
}
| [
"AlexeyShv992@gmail.com"
] | AlexeyShv992@gmail.com |
19ca7fe5908fbfc3491205e7ef72e6cc5ef5641f | 12c608d9290d624263e8e0f30208943f4a503e78 | /Lights/PointLight.h | fe798cd58bf54d5f5542ad5b0da25b4454b2ec3f | [] | no_license | lwfitzgerald/raytracer | 430fb68b167a93f165412462e66135818a013bf9 | 64d15fabf7eaadde8bd9e72e0e470051dec49c7e | refs/heads/master | 2021-05-29T16:33:21.722132 | 2012-04-24T01:14:55 | 2012-04-24T01:14:55 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 858 | h | #ifndef POINTLIGHT_H_
#define POINTLIGHT_H_
#include "Light.h"
#include "../Utils/Point3.h"
namespace Raytracer {
class PointLight: public Light {
public:
PointLight();
/**
* Construct a Point Light from an istringstream
*/
PointLight(std::istringstream& iss);
virtual ~PointLight() {}
virtual Vector3 getDirection(const ShadeInfo& shadeInfo) const;
virtual Vector3 getDirectionToHitPoint(const ShadeInfo& shadeInfo) const;
virtual Colour getRadiance(const ShadeInfo& shadeInfo) const;
/**
* Set the position of the Point Light
*/
void setPosition(const Point3& position);
virtual bool inShadow(const ShadeInfo& shadeInfo, const World& world) const;
protected:
Point3 position;
};
}
#endif /* POINTLIGHT_H_ */
| [
"lw.fitzgerald@gmail.com"
] | lw.fitzgerald@gmail.com |
03d7b1af3381918ad09d6a3482ad3fc4030b4d2e | 3ff1fe3888e34cd3576d91319bf0f08ca955940f | /cwp/include/tencentcloud/cwp/v20180228/model/CheckBashRuleParamsRequest.h | 9543e0612326b7f64ba1f592ea585481bf091f66 | [
"Apache-2.0"
] | permissive | TencentCloud/tencentcloud-sdk-cpp | 9f5df8220eaaf72f7eaee07b2ede94f89313651f | 42a76b812b81d1b52ec6a217fafc8faa135e06ca | refs/heads/master | 2023-08-30T03:22:45.269556 | 2023-08-30T00:45:39 | 2023-08-30T00:45:39 | 188,991,963 | 55 | 37 | Apache-2.0 | 2023-08-17T03:13:20 | 2019-05-28T08:56:08 | C++ | UTF-8 | C++ | false | false | 6,792 | h | /*
* Copyright (c) 2017-2019 THL A29 Limited, a Tencent company. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef TENCENTCLOUD_CWP_V20180228_MODEL_CHECKBASHRULEPARAMSREQUEST_H_
#define TENCENTCLOUD_CWP_V20180228_MODEL_CHECKBASHRULEPARAMSREQUEST_H_
#include <string>
#include <vector>
#include <map>
#include <tencentcloud/core/AbstractModel.h>
namespace TencentCloud
{
namespace Cwp
{
namespace V20180228
{
namespace Model
{
/**
* CheckBashRuleParams่ฏทๆฑๅๆฐ็ปๆไฝ
*/
class CheckBashRuleParamsRequest : public AbstractModel
{
public:
CheckBashRuleParamsRequest();
~CheckBashRuleParamsRequest() = default;
std::string ToJsonString() const;
/**
* ่ทๅๆ ก้ชๅ
ๅฎน NameๆRule ๏ผไธคไธช้ฝ่ฆๆ ก้ชๆถ้ๅทๅๅฒ
* @return CheckField ๆ ก้ชๅ
ๅฎน NameๆRule ๏ผไธคไธช้ฝ่ฆๆ ก้ชๆถ้ๅทๅๅฒ
*
*/
std::string GetCheckField() const;
/**
* ่ฎพ็ฝฎๆ ก้ชๅ
ๅฎน NameๆRule ๏ผไธคไธช้ฝ่ฆๆ ก้ชๆถ้ๅทๅๅฒ
* @param _checkField ๆ ก้ชๅ
ๅฎน NameๆRule ๏ผไธคไธช้ฝ่ฆๆ ก้ชๆถ้ๅทๅๅฒ
*
*/
void SetCheckField(const std::string& _checkField);
/**
* ๅคๆญๅๆฐ CheckField ๆฏๅฆๅทฒ่ตๅผ
* @return CheckField ๆฏๅฆๅทฒ่ตๅผ
*
*/
bool CheckFieldHasBeenSet() const;
/**
* ่ทๅๅจไบไปถๅ่กจไธญๆฐๅข็ฝๅๆถ้่ฆๆไบคไบไปถID
* @return EventId ๅจไบไปถๅ่กจไธญๆฐๅข็ฝๅๆถ้่ฆๆไบคไบไปถID
*
*/
uint64_t GetEventId() const;
/**
* ่ฎพ็ฝฎๅจไบไปถๅ่กจไธญๆฐๅข็ฝๅๆถ้่ฆๆไบคไบไปถID
* @param _eventId ๅจไบไปถๅ่กจไธญๆฐๅข็ฝๅๆถ้่ฆๆไบคไบไปถID
*
*/
void SetEventId(const uint64_t& _eventId);
/**
* ๅคๆญๅๆฐ EventId ๆฏๅฆๅทฒ่ตๅผ
* @return EventId ๆฏๅฆๅทฒ่ตๅผ
*
*/
bool EventIdHasBeenSet() const;
/**
* ่ทๅๅกซๅ
ฅ็่งๅๅ็งฐ
* @return Name ๅกซๅ
ฅ็่งๅๅ็งฐ
*
*/
std::string GetName() const;
/**
* ่ฎพ็ฝฎๅกซๅ
ฅ็่งๅๅ็งฐ
* @param _name ๅกซๅ
ฅ็่งๅๅ็งฐ
*
*/
void SetName(const std::string& _name);
/**
* ๅคๆญๅๆฐ Name ๆฏๅฆๅทฒ่ตๅผ
* @return Name ๆฏๅฆๅทฒ่ตๅผ
*
*/
bool NameHasBeenSet() const;
/**
* ่ทๅ็จๆทๅกซๅ
ฅ็ๆญฃๅ่กจ่พพๅผ๏ผ"ๆญฃๅ่กจ่พพๅผ" ้ไธ "ๆไบคEventIdๅฏนๅบ็ๅฝไปคๅ
ๅฎน" ็ธๅน้
* @return Rule ็จๆทๅกซๅ
ฅ็ๆญฃๅ่กจ่พพๅผ๏ผ"ๆญฃๅ่กจ่พพๅผ" ้ไธ "ๆไบคEventIdๅฏนๅบ็ๅฝไปคๅ
ๅฎน" ็ธๅน้
*
*/
std::string GetRule() const;
/**
* ่ฎพ็ฝฎ็จๆทๅกซๅ
ฅ็ๆญฃๅ่กจ่พพๅผ๏ผ"ๆญฃๅ่กจ่พพๅผ" ้ไธ "ๆไบคEventIdๅฏนๅบ็ๅฝไปคๅ
ๅฎน" ็ธๅน้
* @param _rule ็จๆทๅกซๅ
ฅ็ๆญฃๅ่กจ่พพๅผ๏ผ"ๆญฃๅ่กจ่พพๅผ" ้ไธ "ๆไบคEventIdๅฏนๅบ็ๅฝไปคๅ
ๅฎน" ็ธๅน้
*
*/
void SetRule(const std::string& _rule);
/**
* ๅคๆญๅๆฐ Rule ๆฏๅฆๅทฒ่ตๅผ
* @return Rule ๆฏๅฆๅทฒ่ตๅผ
*
*/
bool RuleHasBeenSet() const;
/**
* ่ทๅ็ผ่พๆถไผ ็่งๅid
* @return Id ็ผ่พๆถไผ ็่งๅid
*
*/
uint64_t GetId() const;
/**
* ่ฎพ็ฝฎ็ผ่พๆถไผ ็่งๅid
* @param _id ็ผ่พๆถไผ ็่งๅid
*
*/
void SetId(const uint64_t& _id);
/**
* ๅคๆญๅๆฐ Id ๆฏๅฆๅทฒ่ตๅผ
* @return Id ๆฏๅฆๅทฒ่ตๅผ
*
*/
bool IdHasBeenSet() const;
private:
/**
* ๆ ก้ชๅ
ๅฎน NameๆRule ๏ผไธคไธช้ฝ่ฆๆ ก้ชๆถ้ๅทๅๅฒ
*/
std::string m_checkField;
bool m_checkFieldHasBeenSet;
/**
* ๅจไบไปถๅ่กจไธญๆฐๅข็ฝๅๆถ้่ฆๆไบคไบไปถID
*/
uint64_t m_eventId;
bool m_eventIdHasBeenSet;
/**
* ๅกซๅ
ฅ็่งๅๅ็งฐ
*/
std::string m_name;
bool m_nameHasBeenSet;
/**
* ็จๆทๅกซๅ
ฅ็ๆญฃๅ่กจ่พพๅผ๏ผ"ๆญฃๅ่กจ่พพๅผ" ้ไธ "ๆไบคEventIdๅฏนๅบ็ๅฝไปคๅ
ๅฎน" ็ธๅน้
*/
std::string m_rule;
bool m_ruleHasBeenSet;
/**
* ็ผ่พๆถไผ ็่งๅid
*/
uint64_t m_id;
bool m_idHasBeenSet;
};
}
}
}
}
#endif // !TENCENTCLOUD_CWP_V20180228_MODEL_CHECKBASHRULEPARAMSREQUEST_H_
| [
"tencentcloudapi@tencent.com"
] | tencentcloudapi@tencent.com |
774474f6153ebe1ca5745b1f9e876bd545d2eb46 | 1f6824a64c3cc6b0827b55f24079edc23ed6bc2b | /Plugins/VoxelFree/Intermediate/Build/Win64/UE4Editor/Inc/VoxelEditorDefault/VoxelEditorDefault.init.gen.cpp | 0c8d5105e10a2fa280f9ab52df4dd5f39ecf8abe | [
"MIT"
] | permissive | lineCode/Woodlands | bb330644567c92e041e4da3d5d80326755c370c5 | 9e99f948543ad3f8f0eead691eddb4125da272f5 | refs/heads/master | 2023-04-15T13:56:45.978505 | 2021-04-19T04:30:44 | 2021-04-19T04:30:44 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,094 | cpp | // Copyright Epic Games, Inc. All Rights Reserved.
/*===========================================================================
Generated code exported from UnrealHeaderTool.
DO NOT modify this manually! Edit the corresponding .h files instead!
===========================================================================*/
#include "UObject/GeneratedCppIncludes.h"
#ifdef _MSC_VER
#pragma warning (push)
#pragma warning (disable : 4883)
#endif
PRAGMA_DISABLE_DEPRECATION_WARNINGS
void EmptyLinkFunctionForGeneratedCodeVoxelEditorDefault_init() {}
UPackage* Z_Construct_UPackage__Script_VoxelEditorDefault()
{
static UPackage* ReturnPackage = nullptr;
if (!ReturnPackage)
{
static const UE4CodeGen_Private::FPackageParams PackageParams = {
"/Script/VoxelEditorDefault",
nullptr,
0,
PKG_CompiledIn | 0x00000040,
0xB5D724CE,
0x4237F087,
METADATA_PARAMS(nullptr, 0)
};
UE4CodeGen_Private::ConstructUPackage(ReturnPackage, PackageParams);
}
return ReturnPackage;
}
PRAGMA_ENABLE_DEPRECATION_WARNINGS
#ifdef _MSC_VER
#pragma warning (pop)
#endif
| [
"Mattrb_99@ymail.com"
] | Mattrb_99@ymail.com |
ae81eef0e34744b12f3bc67b3fa351f8c4812aa4 | 8edde9d2e5cea812b4b3db859d2202d0a65cb800 | /Documentation/Code/Engine/Graphics/GrModelNode.cpp | 6e84e27c81322846ceaf3146cae94c9c9b303513 | [
"MIT"
] | permissive | shawwn/bootstrap | 751cb00175933f91a2e5695d99373fca46a0778e | 39742d2a4b7d1ab0444d9129152252dfcfb4d41b | refs/heads/master | 2023-04-09T20:41:05.034596 | 2023-03-28T17:43:50 | 2023-03-28T17:43:50 | 130,915,922 | 0 | 0 | null | null | null | null | WINDOWS-1252 | C++ | false | false | 12,930 | cpp | //----------------------------------------------------------
//! File: GrModelNode.cpp
//! Author: Kevin Bray
//! Created: 04-02-06
//! Copyright ยฉ 2004 Bootstrap Studios. All rights reserved.
//----------------------------------------------------------
#include "graphics_afx.h"
//! class header.
#include "GrModelNode.h"
//! project includes.
#include "GrModel.h"
#include "GrMeshInst.h"
#include "GrPolygonNode.h"
#include "GrPolygonMesh.h"
#include "UWriter.h"
#include "UReader.h"
#include "GrFrustum.h"
#include "MSphere.h"
#include "GrScene.h"
#include "GrLight.h"
#include "GrLightMgr.h"
#include "GrRenderList.h"
//**********************************************************
//! class GrModelNode
//**********************************************************
//==========================================================
//! ctor & dtor
//==========================================================
//----------------------------------------------------------
GrModelNode::GrModelNode( GrModel* owner, GrModelNode* parent, const MMat4x4& local, GrMeshInst* meshInst )
: _owner( owner )
, _parent( parent )
, _local( local )
{
B_ASSERT( owner != 0 );
}
//----------------------------------------------------------
GrModelNode::GrModelNode( GrModel* owner, GrPolygonNode* fromTree )
: _owner( owner )
, _parent( 0 )
{
B_ASSERT( owner != 0 );
//! generate a list of meshes.
UFastArray< URef< GrPolygonMesh > > polyMeshes;
fromTree->BuildMeshList( polyMeshes );
//! build database mapping poly meshes to renderable meshes.
std::map< tstring, std::vector< GrMeshInst* > > meshes;
for ( unsigned int i = 0; i < polyMeshes.GetElemCount(); ++i )
{
//! get the poly mesh we need to generate renderable meshes from.
URef< GrPolygonMesh > curPolyMesh = polyMeshes[ i ];
//! skip if the mesh was already added to our database.
if ( meshes.find( curPolyMesh->GetName() ) != meshes.end() )
continue;
//! add an entry to our database.
std::vector< GrMeshInst* >& meshVec = meshes[ curPolyMesh->GetName() ];
curPolyMesh->GenMeshes( meshVec );
}
//! now build the node tree.
InitFromPolyNode( owner, fromTree, meshes );
//! free up our meshes.
std::map< tstring, std::vector< GrMeshInst* > >::iterator iter = meshes.begin();
for ( ; iter != meshes.end(); ++iter )
{
for ( unsigned int i = 0; i < iter->second.size(); ++i )
delete iter->second[ i ];
}
}
//----------------------------------------------------------
GrModelNode::GrModelNode( GrModel* owner, GrPolygonNode* fromTree, const std::map< tstring, std::vector< GrMeshInst* > >& meshes )
: _owner( owner )
, _parent( 0 )
{
InitFromPolyNode( owner, fromTree, meshes );
}
//----------------------------------------------------------
GrModelNode::GrModelNode( GrModel* owner, UReader& reader, const UFastArray< URef< GrMesh > >& meshes,
unsigned short majorVer, unsigned short minorVer )
: _owner( owner )
, _parent( 0 )
{
Load( owner, reader, meshes, majorVer, minorVer );
}
//----------------------------------------------------------
GrModelNode::~GrModelNode()
{
unsigned int childCount = _children.GetElemCount();
for ( unsigned int i = 0; i < childCount; ++i )
delete _children[ i ];
unsigned int meshCount = _meshes.GetElemCount();
for ( unsigned int i = 0; i < meshCount; ++i )
delete _meshes[ i ];
}
//==========================================================
//! public methods
//==========================================================
//----------------------------------------------------------
GrModelNode*
GrModelNode::Clone( GrModel* newOwner, bool deep, GrModelNode* parent )
{
//! create a new model node.
GrModelNode* newNode = new GrModelNode( newOwner, parent, _local );
newNode->_name = _name;
//! clone mesh instances.
for ( unsigned int i = 0; i < _meshes.GetElemCount(); ++i )
newNode->_meshes.Push( _meshes[ i ]->Clone( deep ) );
//! recurse for children.
for ( unsigned int i = 0; i < _children.GetElemCount(); ++i )
newNode->_children.Push( _children[ i ]->Clone( newOwner, deep, newNode ) );
//! return the newly created node.
return newNode;
}
//----------------------------------------------------------
void
GrModelNode::SetLocal( const MMat4x4& local )
{
//! mark the owner as dirty.
_owner->MarkAsDirty();
_local = local;
}
//----------------------------------------------------------
GrModelNode*
GrModelNode::GetChild( unsigned int idx )
{
B_ASSERT( idx < _children.GetElemCount() );
return _children[ idx ];
}
//----------------------------------------------------------
GrModelNode*
GrModelNode::FindNode( const char* name, bool ignoreCase )
{
if ( ignoreCase )
{
if ( _stricmp( _name.c_str(), name ) == 0 )
return this;
}
else
{
if ( strcmp( _name.c_str(), name ) == 0 )
return this;
}
//! recurse.
for ( unsigned int i = 0; i < _children.GetElemCount(); ++i )
{
GrModelNode* found = _children[ i ]->FindNode( name, ignoreCase );
if ( found )
return found;
}
//! not found!
return 0;
}
//----------------------------------------------------------
GrMeshInst*
GrModelNode::GetMeshInst( unsigned int idx ) const
{
B_ASSERT( idx < GetMeshInstCount() );
return _meshes[ idx ];
}
//----------------------------------------------------------
void
GrModelNode::Update( const MMat4x4& parentMatrix )
{
//! calculate our new world matrix.
_world = parentMatrix * _local;
//! propagate the transform to the mesh instances if necessary.
unsigned int meshCount = _meshes.GetElemCount();
for ( unsigned int i = 0; i < meshCount; ++i )
_meshes[ i ]->SetTransform( _world );
//! update children.
for ( unsigned int i = 0; i < _children.GetElemCount(); ++i )
_children[ i ]->Update( _world );
}
//----------------------------------------------------------
void
GrModelNode::CalcBounds( MAABox& bounds )
{
//! recurse to children.
unsigned int childCount = _children.GetElemCount();
for ( unsigned int i = 0; i < childCount; ++i )
_children[ i ]->CalcBounds( bounds );
//! evaluate mesh bounds.
unsigned int meshCount = _meshes.GetElemCount();
for ( unsigned int i = 0; i < meshCount; ++i )
bounds.AddBoxToVolume( _meshes[ i ]->GetOBox() );
}
//----------------------------------------------------------
bool
GrModelNode::CalcBoundsExact( MAABox& bounds, bool boundsInit )
{
//! recurse to children.
unsigned int childCount = _children.GetElemCount();
for ( unsigned int i = 0; i < childCount; ++i )
boundsInit = _children[ i ]->CalcBoundsExact( bounds, boundsInit );
//! evaluate mesh bounds.
if ( boundsInit )
{
unsigned int meshCount = _meshes.GetElemCount();
for ( unsigned int i = 0; i < meshCount; ++i )
bounds.AddBoxToVolume( _meshes[ i ]->GetOBox() );
}
else
{
unsigned int meshCount = _meshes.GetElemCount();
for ( unsigned int i = 0; i < meshCount; ++i )
{
if ( !boundsInit )
{
bounds = MAABox( _meshes[ i ]->GetOBox() );
boundsInit = true;
}
else
bounds.AddBoxToVolume( _meshes[ i ]->GetOBox() );
}
}
return boundsInit;
}
//----------------------------------------------------------
const
MMat4x4&
GrModelNode::GetWorld() const
{
return _world;
}
//----------------------------------------------------------
void
GrModelNode::SetWorld( const MMat4x4& transform )
{
//! ensure that our owner has updated us.
_owner->EnsureUpdated();
//! grab our parent's worldspace transform.
MMat4x4 parentWorld;
if ( _parent )
parentWorld = _parent->GetWorld();
else
parentWorld = _owner->GetWorld();
//! invert it.
MMat4x4 parentWorldInv;
bool success = parentWorld.Inverse( parentWorldInv );
B_ASSERT( success );
if ( success )
{
//! transform the incoming matrix into localspace
//! and store our new transforms.
_local = parentWorldInv * transform;
_world = transform;
//! mark the owner as dirty.
_owner->MarkAsDirty();
}
}
//----------------------------------------------------------
void
GrModelNode::BuildMeshList( UFastArray< URef< GrMesh > >& meshes )
{
//! add any meshes to the mesh list that have not already been added.
for ( unsigned int i = 0; i < _meshes.GetElemCount(); ++i )
{
unsigned int j = 0;
for ( ; j < meshes.GetElemCount(); ++j )
{
if ( _meshes[ i ]->GetMesh() == meshes[ j ] )
break;
}
if ( j == meshes.GetElemCount() )
{
meshes.Push( _meshes[ i ]->GetMesh() );
}
}
//! recurse.
for ( unsigned int i = 0; i < _children.GetElemCount(); ++i )
_children[ i ]->BuildMeshList( meshes );
}
//----------------------------------------------------------
void
GrModelNode::Optimize()
{
for ( unsigned int i = 0; i < _meshes.GetElemCount(); ++i )
_meshes[ i ]->GetMesh()->Optimize();
}
//----------------------------------------------------------
void
GrModelNode::Cache()
{
for ( unsigned int i = 0; i < _meshes.GetElemCount(); ++i )
_meshes[ i ]->Cache();
for ( unsigned int i = 0; i < _children.GetElemCount(); ++i )
_children[ i ]->Cache();
}
//----------------------------------------------------------
void
GrModelNode::Evict()
{
for ( unsigned int i = 0; i < _meshes.GetElemCount(); ++i )
_meshes[ i ]->Evict();
for ( unsigned int i = 0; i < _children.GetElemCount(); ++i )
_children[ i ]->Evict();
}
//----------------------------------------------------------
void
GrModelNode::Save( UWriter& writer ) const
{
//! save the name.
writer.WriteString( _name );
//! save the local transform.
_local.Save( writer );
//! save the light link.
// writer.WriteString( _light ? _light->GetId().GetPathString() : "" );
//! save mesh links.
writer.WriteInt( _meshes.GetElemCount() );
for ( unsigned int i = 0; i < _meshes.GetElemCount(); ++i )
{
_meshes[ i ]->Save( writer );
}
//! save children.
writer.WriteInt( _children.GetElemCount() );
for ( unsigned int i = 0; i < _children.GetElemCount(); ++i )
{
_children[ i ]->Save( writer );
}
}
//----------------------------------------------------------
void
GrModelNode::GetRenderableObjects( GrRenderList& lightReceivers, GrRenderList* shadowCasters ) const
{
for ( unsigned int i = 0; i < _meshes.GetElemCount(); ++i )
{
lightReceivers.AddMeshInst( _meshes[ i ], false );
if ( shadowCasters )
shadowCasters->AddMeshInst( _meshes[ i ], false );
}
//! recurse.
for ( unsigned int i = 0; i < _children.GetElemCount(); ++i )
_children[ i ]->GetRenderableObjects( lightReceivers, shadowCasters );
}
//==========================================================
//! private methods
//==========================================================
//----------------------------------------------------------
void
GrModelNode::InitFromPolyNode( GrModel* owner, GrPolygonNode* fromTree,
const std::map< tstring, std::vector< GrMeshInst* > >& meshes )
{
//! get our name.
_name = fromTree->GetName();
//! store our transform.
_local = fromTree->GetLocal();
//! add meshes.
unsigned int meshCount = fromTree->GetMeshCount();
for ( unsigned int i = 0; i < meshCount; ++i )
{
//! get the poly mesh.
URef< GrPolygonMesh > polyMesh = fromTree->GetMesh( i );
const tstring& polyMeshName = polyMesh->GetName();
//! check to see if an entry for the poly mesh exists.
std::map< tstring, std::vector< GrMeshInst* > >::const_iterator iter = meshes.find( polyMeshName );
if ( iter != meshes.end() )
{
const std::vector< GrMeshInst* >& meshInstVec = iter->second;
for ( unsigned int i = 0; i < meshInstVec.size(); ++i )
{
_meshes.Push( meshInstVec[ i ]->Clone( false ) );
}
}
}
//! recurse for children.
unsigned int childCount = fromTree->GetChildCount();
for ( unsigned int i = 0; i < childCount; ++i )
{
//! create the new child node.
GrPolygonNode* curChild = fromTree->GetChild( i );
GrModelNode* newChild = new GrModelNode( owner, curChild, meshes );
//! add the child to our list and set it's parent to this.
_children.Push( newChild );
newChild->_parent = this;
}
}
//----------------------------------------------------------
void
GrModelNode::Load( GrModel* owner, UReader& reader, const UFastArray< URef< GrMesh > >& meshes,
unsigned short majorVer, unsigned short minorVer )
{
//! load the name.
_name = reader.ReadString();
//! load the local transform.
_local.Load( reader );
//! if we have an old version of the file, check for an attached
//! light. Note that this simply gets ignored.
if ( majorVer <= 1 && minorVer < 1 )
reader.ReadString();
//! load mesh links.
unsigned int meshInstCount = reader.ReadInt();
for ( unsigned int i = 0; i < meshInstCount; ++i )
_meshes.Push( new GrMeshInst( reader, meshes ) );
//! load children.
unsigned int childCount = reader.ReadInt();
for ( unsigned int i = 0; i < childCount; ++i )
{
GrModelNode* node = new GrModelNode( owner, reader, meshes, majorVer, minorVer );
node->_parent = this;
_children.Push( node );
}
}
| [
"shawnpresser@gmail.com"
] | shawnpresser@gmail.com |
db6d9f59ceb3d0535b00dd62b20a01e1e6271586 | 1461cce7c69e7391bc8c4c6bcccc9402bbb2ba12 | /MinimumCostOfTickets.cpp | 3b778472e79cc8dc709540e50791b8fe246c7e06 | [] | no_license | Kharanshu31/August-Leetcode | c296ec4e56ac72ac15a82dcf127316000c345bd8 | 444502e03facd89675442da338f23dfa0bc5f5ae | refs/heads/master | 2022-12-14T23:47:55.183717 | 2020-09-07T09:53:40 | 2020-09-07T09:53:40 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 703 | cpp | class Solution {
public:
int mincostTickets(vector<int>& days, vector<int>& costs) {
map<int,int>m;
for(int i=0;i<days.size();i++)
m[days[i]]++;
int dp[366];
dp[0]=0;
for(int i=1;i<=365;i++)
{
if(!m.count(i))
dp[i]=dp[i-1];
else
{
int day1=dp[i-1]+costs[0];
int day7=dp[max(0,i-7)]+costs[1];
int day30=dp[max(0,i-30)]+costs[2];
dp[i]=min(day1,min(day7,day30));
}
}
return dp[365];
}
};
| [
"noreply@github.com"
] | Kharanshu31.noreply@github.com |
2cf2e815cc3f789dd1222a294f20e99c372b0690 | 5838cf8f133a62df151ed12a5f928a43c11772ed | /NT/printscan/inc/psutil/cntutils.inl | 8d440ba696dd9577401752c4f43dcc3edbc9e1fa | [] | no_license | proaholic/Win2K3 | e5e17b2262f8a2e9590d3fd7a201da19771eb132 | 572f0250d5825e7b80920b6610c22c5b9baaa3aa | refs/heads/master | 2023-07-09T06:15:54.474432 | 2021-08-11T09:09:14 | 2021-08-11T09:09:14 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,047 | inl | /*****************************************************************************
*
* (C) COPYRIGHT MICROSOFT CORPORATION, 2000
*
* TITLE: cntutils.inl
*
* VERSION: 1.0
*
* AUTHOR: LazarI
*
* DATE: 23-Dec-2000
*
* DESCRIPTION: Containers and algorithms utility templates (Impl.)
*
*****************************************************************************/
////////////////////////////////////////////////
//
// class CFastHeap<T>
//
// fast cached heap for fixed chunks
// of memory (MT safe)
//
template <class T>
CFastHeap<T>::CFastHeap<T>(int iCacheSize):
#if DBG
m_iPhysicalAllocs(0),
m_iLogicalAllocs(0),
#endif
m_pFreeList(NULL),
m_iCacheSize(iCacheSize),
m_iCached(0)
{
// nothing
}
template <class T>
CFastHeap<T>::~CFastHeap<T>()
{
// delete the cache
while( m_pFreeList )
{
HeapItem *pItem = m_pFreeList;
m_pFreeList = m_pFreeList->pNext;
delete pItem;
#if DBG
m_iPhysicalAllocs--;
#endif
}
#if DBG
ASSERT(0 == m_iPhysicalAllocs);
ASSERT(0 == m_iLogicalAllocs);
#endif
}
template <class T>
HRESULT CFastHeap<T>::Alloc(const T &data, HANDLE *ph)
{
CCSLock::Locker lock(m_csLock);
HRESULT hr = E_INVALIDARG;
if( ph )
{
*ph = NULL;
HeapItem *pi = NULL;
if( m_pFreeList )
{
// we have an item in the cache, just use it
pi = m_pFreeList;
m_pFreeList = m_pFreeList->pNext;
m_iCached--;
ASSERT(m_iCached >= 0);
}
else
{
// no items in the cache, allocate new one
pi = new HeapItem;
#if DBG
if( pi )
{
m_iPhysicalAllocs++;
}
#endif
}
if( pi )
{
pi->data = data;
*ph = reinterpret_cast<HANDLE>(pi);
#if DBG
m_iLogicalAllocs++;
#endif
}
hr = (*ph) ? S_OK : E_OUTOFMEMORY;
}
return hr;
}
template <class T>
HRESULT CFastHeap<T>::Free(HANDLE h)
{
CCSLock::Locker lock(m_csLock);
HRESULT hr = E_INVALIDARG;
if( h )
{
#if DBG
m_iLogicalAllocs--;
#endif
ASSERT(m_iCached >= 0);
HeapItem *pi = reinterpret_cast<HeapItem*>(h);
if( m_iCached < m_iCacheSize )
{
// the number of cached items is less than the
// cache size, so we put this item in the cache
pi->pNext = m_pFreeList;
m_pFreeList = pi;
m_iCached++;
}
else
{
// enough items cached, delete this one
delete pi;
#if DBG
m_iPhysicalAllocs--;
#endif
}
hr = S_OK;
}
return hr;
}
template <class T>
HRESULT CFastHeap<T>::GetItem(HANDLE h, T **ppData)
{
// just return the item ptr. no need to aquire the CS as this is
// readonly function and Alloc/Free cannot invalidate the item.
*ppData = &(reinterpret_cast<HeapItem*>(h)->data);
return S_OK;
}
| [
"blindtiger@foxmail.com"
] | blindtiger@foxmail.com |
6ae5420952f9474de2d8c9e87730b8b46260e329 | fbb231cebffddbb9cd2d87d754d775e840c18d8d | /uva/11466.cpp | 4681ecf0037e6c4b0ca391e9c50d943663c17532 | [] | no_license | Pkataki/Problem_Solving | ae6b1c8334436d25388f2ec460ed07200a1db23e | abdd7f04f1fee46025036b5594e9d0ca3ec07907 | refs/heads/master | 2021-10-11T13:02:22.351252 | 2019-01-26T01:16:47 | 2019-01-26T01:16:47 | 112,233,360 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 419 | cpp | #include<bits/stdc++.h>
using namespace std;
main()
{
ios_base::sync_with_stdio(0);
int n;
while(cin >> n && n)
{
int cont = 0;
int ans = -1;
if(n < 0)
n *= -1;
for(int i = 2; i*i <= n && n != 1; i++)
{
while(n % i == 0)
{
ans = i;
n /= i;
}
if(ans == i)
cont++;
}
if(n != 1 && ans != -1)
{
ans = n;
}
else if(cont == 1)
ans = -1;
cout << ans << '\n';
}
}
| [
"paulogkataki@hotmail.com"
] | paulogkataki@hotmail.com |
883929040e72f53e651dc1112d5d76fd0755a92c | d8aa7ddfbec886b243cd59a9c6e3c7df3c9d5f14 | /dlib/config_reader/config_reader_thread_safe_abstract.h | dd49b63798d894bba78b54f3785c6560400dc0e9 | [
"BSD-2-Clause",
"BSL-1.0"
] | permissive | loran4d/mud | 64e0840bc707141caeb16f8cb2dddb018e1fac27 | 2e0bbae7e4ca242f075f2b31b41a3856ad8469dd | refs/heads/main | 2023-08-22T00:19:46.136790 | 2021-11-01T21:31:03 | 2021-11-01T21:31:03 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,582 | h | // Copyright (C) 2007 Davis E. King (davisking@users.sourceforge.net)
// License: Boost Software License See LICENSE.txt for the full license.
#undef DLIB_CONFIG_READER_THREAD_SAFe_ABSTRACT_
#ifdef DLIB_CONFIG_READER_THREAD_SAFe_ABSTRACT_
#include <string>
#include <iosfwd>
#include "config_reader_kernel_abstract.h"
#include "../threads/threads_kernel_abstract.h"
namespace dlib
{
template <
typename config_reader_base
>
class config_reader_thread_safe
{
/*!
REQUIREMENTS ON config_reader_base
is an implementation of config_reader/config_reader_kernel_abstract.h
WHAT THIS EXTENSION DOES FOR config_reader
This object extends a normal config_reader by simply wrapping all
its member functions inside mutex locks to make it safe to use
in a threaded program.
So this object provides an interface identical to the one defined
in the config_reader/config_reader_kernel_abstract.h file except that
the rmutex returned by get_mutex() is always locked when this
object's member functions are called.
!*/
public:
const rmutex& get_mutex (
) const;
/*!
ensures
- returns the rmutex used to make this object thread safe. i.e. returns
the rmutex that is locked when this object's functions are called.
!*/
};
}
#endif // DLIB_CONFIG_READER_THREAD_SAFe_ABSTRACT_
| [
"game-source@254f5b4c-bdf4-4503-907e-934c7b59e499"
] | game-source@254f5b4c-bdf4-4503-907e-934c7b59e499 |
908f7b92f45b2f0727834fa87e637f8e1316ecc3 | f332d14232eeeded179ce8f0a146eeb950c80502 | /admin.cpp | fbb68a93f70c3f7bbcbb6692e9166144dfd5ffc9 | [] | no_license | Wassim-Aloui/Smart_Cinema | 6033f14d0d812bedc4fddf454f724356064c693c | 5a24ad7578095995e383459ee897224bd2bc979f | refs/heads/main | 2023-04-13T21:29:35.292092 | 2021-01-11T18:40:54 | 2021-01-11T18:40:54 | 314,878,298 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,597 | cpp | #include "admin.h"
#include <QSqlQuery>
Admin::Admin()
{
id=0;
nom="";
prenom="";
username="";
password="";
}
Admin::Admin(int id,QString nom,QString prenom,QString username,QString password )
{
this->id=id;
this->nom=nom;
this->prenom=prenom;
this->username=username;
this->password=password;
}
Admin::~Admin()
{
}
QString Admin::getNom(){
return nom;
}
void Admin::setNom(QString nom){
this->nom=nom;
}
int Admin::getId(){
return id;
}
void Admin::setId(int id){
this->id=id;
}
QString Admin::getusername(){
return username;
}
void Admin::setusername(QString username){
this->username=username;
}
QString Admin::getpassword(){
return password;
}
void Admin::setpassword(QString password){
this->password=password;
}
bool Admin::ajouter(){
QSqlQuery query;
query.prepare("insert into compte (id,nom,prenom,username,password) values (:id,:nom,:prenom,:username,:password)");
query.bindValue(":id",id);
query.bindValue(":nom",nom);
query.bindValue(":prenom",prenom);
query.bindValue(":username",username);
query.bindValue(":password",password);
return query.exec();
}
bool Admin::supprimer(int id){
QSqlQuery q;
q.prepare("select * from compte where id=:id");
q.bindValue(":id",id);
q.exec();
int total=0; //mch mawjoud mayfasakhch
while(q.next()){
total++;
}
if(total==1){
QSqlQuery query;
query.prepare("delete from compte where id=:id");
query.bindValue(":id",id);
return query.exec();
}
else{
return false;
}
}
bool Admin::modifier(int idc ,QString nom,QString prenom,QString username,QString password){
QSqlQuery query;
query.prepare("update compte set nom=:nom,prenom=:prenom,username=:username,password=:password where id=:idc");
query.bindValue(":id",id);
query.bindValue(":nom",nom);
query.bindValue(":prenom",prenom);
query.bindValue(":username",username);
query.bindValue(":password",password);
query.bindValue(":idc",idc);
return query.exec();
}
QSqlQueryModel * Admin::afficher(){
QSqlQueryModel * model=new QSqlQueryModel();
model->setQuery("select * from compte");
model->setHeaderData(0, Qt::Horizontal, QObject::tr("ID"));
model->setHeaderData(1, Qt::Horizontal, QObject::tr("NOM"));
model->setHeaderData(2, Qt::Horizontal, QObject::tr("PRENOM"));
model->setHeaderData(3, Qt::Horizontal, QObject::tr("USERNAME"));
return model;
}
/*
QSqlQueryModel * Admin::chercher_Salle_par_nom(QString m)
{
{QSqlQueryModel *model = new QSqlQueryModel;
model->setQuery("SELECT * FROM Salle WHERE NOMSALLE like '"+m+"%' ");
model->setHeaderData(0, Qt::Horizontal, QObject::tr("ID"));
model->setHeaderData(1, Qt::Horizontal, QObject::tr("NOMSALLE"));
model->setHeaderData(2, Qt::Horizontal, QObject::tr("NUMBLOC"));
model->setHeaderData(3, Qt::Horizontal, QObject::tr("CAPACITE"));
return model ;
}
}
QSqlQueryModel *Admin::chercher_Salle_par_id(QString idd)
{
{
QSqlQueryModel *model = new QSqlQueryModel;
model->setQuery("SELECT * FROM Salle WHERE ID like '"+idd+"' ");
model->setHeaderData(0, Qt::Horizontal, QObject::tr("ID"));
model->setHeaderData(1, Qt::Horizontal, QObject::tr("NOMSALLE"));
model->setHeaderData(2, Qt::Horizontal, QObject::tr("NUMBLOC"));
model->setHeaderData(3, Qt::Horizontal, QObject::tr("CAPACITE"));
return model ;
}
}
QSqlQueryModel * Admin::chercher_Salle_par_capacite(QString m)
{
{QSqlQueryModel *model = new QSqlQueryModel;
model->setQuery("SELECT * FROM Salle WHERE capacite like '"+m+"%' ");
model->setHeaderData(0, Qt::Horizontal, QObject::tr("ID"));
model->setHeaderData(1, Qt::Horizontal, QObject::tr("NOMSALLE"));
model->setHeaderData(2, Qt::Horizontal, QObject::tr("NUMBLOC"));
model->setHeaderData(3, Qt::Horizontal, QObject::tr("CAPACITE"));
return model ;
}
}
QSqlQueryModel* Admin:: trier()
{
QSqlQueryModel * model=new QSqlQueryModel();
model->setQuery("select * from Salle order by nomsalle ");
model->setHeaderData(0, Qt::Horizontal, QObject::tr("ID"));
model->setHeaderData(1, Qt::Horizontal, QObject::tr("NOMSALLE"));
model->setHeaderData(2, Qt::Horizontal, QObject::tr("NUMBLOC"));
model->setHeaderData(3, Qt::Horizontal, QObject::tr("CAPACITE"));
return model;
}
QSqlQueryModel* Admin:: trier1()
{
QSqlQueryModel * model=new QSqlQueryModel();
model->setQuery("select * from Salle order by id desc ");
model->setHeaderData(0, Qt::Horizontal, QObject::tr("ID"));
model->setHeaderData(1, Qt::Horizontal, QObject::tr("NOMSALLE"));
model->setHeaderData(2, Qt::Horizontal, QObject::tr("NUMBLOC"));
model->setHeaderData(3, Qt::Horizontal, QObject::tr("CAPACITE"));
return model;
}
QSqlQueryModel* Admin:: trier2()
{
QSqlQueryModel * model=new QSqlQueryModel();
model->setQuery("select * from Salle order by capacite ");
model->setHeaderData(0, Qt::Horizontal, QObject::tr("ID"));
model->setHeaderData(1, Qt::Horizontal, QObject::tr("NOMSALLE"));
model->setHeaderData(2, Qt::Horizontal, QObject::tr("NUMBLOC"));
model->setHeaderData(3, Qt::Horizontal, QObject::tr("CAPACITE"));
return model;
}*/
QSqlQueryModel* Admin::recherche_nom(QString nom){
QSqlQueryModel *model = new QSqlQueryModel;
model->setQuery("SELECT * FROM Compte WHERE NOM like '"+nom+"' ");
model->setHeaderData(0, Qt::Horizontal, QObject::tr("ID"));
model->setHeaderData(1, Qt::Horizontal, QObject::tr("NOM"));
model->setHeaderData(2, Qt::Horizontal, QObject::tr("PRENOM"));
model->setHeaderData(3, Qt::Horizontal, QObject::tr("USERNAME"));
return model ;
}
bool Admin::verifierExnoms(QString nom){
int i=0;
QSqlQuery query;
query.prepare("select * from compte where NOM= ? ");
query.addBindValue(nom);
if(query.exec())
{while(query.next())
{i++;}}
if(i!=0)
return true ;
else
return false;}
/*
QStringList Admin::listeSalle(){
QSqlQuery query;
query.prepare("select * from Salle");
query.exec();
QStringList list;
while(query.next()){
list.append(query.value(0).toString());
}
return list;
}
QStringList Admin::listSalle1(){
QSqlQuery query;
query.prepare("select * from Salle");
query.exec();
QStringList list;
while(query.next()){
list.append(query.value(5).toString());
}
return list;
}
*/
| [
"wassim.aloui@esprit.tn"
] | wassim.aloui@esprit.tn |
16e1c7bbd3f721a10b2166c9eaac26c78876cb17 | da8f609c1d4cbc892b8772623f31b2c0ea57fe91 | /Algorithm/pat/1019 ่ดจๅ ๆฐ.cpp | 44efde3cf4384e57a4aaf1e5647ac68f71cfa02c | [] | no_license | Nillouise/Algorithm | a92407bd2877d494af1aed99cd8ee063d4ce8cb8 | c52a7c4ced42adb2cf961c147037ba84490bacba | refs/heads/master | 2020-06-15T11:18:21.628395 | 2018-07-28T15:54:16 | 2018-07-28T15:54:16 | 75,299,753 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,157 | cpp | //่ฟ็ง้ข็ฎ่ฆ่่1ๆ่ก
//่ฟไนๆไธพไผ่ถ
ๆถๆฏๅ ไธบ๏ผๆๅคๅช้่ฆๆไธพๅฐi*i,้ฒๆญขๅ ไธบ่พๅ
ฅ็ๆฐๆฏ่ดจๆฐๅฏผ่ด็่ถ
ๆถ๏ผ่ฟๆฏๅพ้่ฆ็๏ผ๏ผ
#include<bits/stdc++.h>
using namespace std;
typedef long long LL;
int main()
{
freopen("input.txt","r",stdin);//
ios::sync_with_stdio(false);
LL n;
cin>>n;
LL t = n;
map<LL,int> but;
while(t%2==0)
{
but[2]++;
t/=2;
}
int first=true;
//่ฟไนๆไธพไผ่ถ
ๆถๆฏๅ ไธบ๏ผๆๅคๅช้่ฆๆไธพๅฐi*i,้ฒๆญขๅ ไธบ่พๅ
ฅ็ๆฐๆฏ่ดจๆฐๅฏผ่ด็่ถ
ๆถ
// for (LL i = 2; t!=1; i+=1)
for (LL i = 3; t>=i*i; i+=2)
{
while(t%i==0){
t/=i;
but[i]++;
}
}
if(t>1)but[t]++;
vector<pair<LL,LL> > ans;
for(auto a:but)
{
ans.push_back({a.first,a.second});
}
cout<<n<<"=";
if(n==1)return cout<<1<<endl,0;//่ฟ็ง้ข็ฎ่ฆ่่1ๆ่ก
for (int i = 0; i < ans.size(); i++)
{
cout<<ans[i].first;
if(ans[i].second>1)cout<<"^"<<ans[i].second;
if(i!=ans.size()-1)cout<<"*";
}
cout<<endl;
return 0;
}
| [
"noreply@github.com"
] | Nillouise.noreply@github.com |
a29d9936baec604489003c4bd65f426ad7d409fa | fb6b653d2f1676b40ab75443edc2a3187cf00606 | /Chapter18/exercises/18.27/Employee.cpp | 9150bcce0a4e6875ea7516483e5547f79d02afce | [] | no_license | wenjing219/Cpp-How-To-Program-9E | 4cd923de658a90f3d3bfd0e4c0b3e8505d3a8472 | 8a6e2d1bc84e94fc598e258b9b151aa40895b21e | refs/heads/master | 2021-01-22T22:16:24.824817 | 2017-03-14T22:14:40 | 2017-03-14T22:14:40 | 85,525,193 | 2 | 0 | null | 2017-03-20T02:04:41 | 2017-03-20T02:04:41 | null | UTF-8 | C++ | false | false | 2,199 | cpp | /*
* =====================================================================================
*
* Filename: Employee.cpp
*
* Description: Exercise 18.27 - Enhanced Employee Class
* Note: No definitions are given for pure virtual functions.
*
* Version: 1.0
* Created: 12/08/16 19:23:10
* Revision: 28/02/17 14:17:15
* Compiler: g++
*
* Author: Siidney Watson - siidney.watson.work@gmail.com
* Organization: LolaDog Studio
*
* =====================================================================================
*/
#include "Employee.h"
#include <iostream>
Employee::Employee(const std::string& first, const std::string& last, const std::string& ssn,
Date dob) :
firstName(first), lastName(last), socialSecurityNumber(ssn), birthDate(dob)
{
}
// set first name
void Employee::setFirstName(const std::string& first){
firstName = first;
}
// get first name
std::string Employee::getFirstName() const{
return firstName;
}
// set last name
void Employee::setLastName(const std::string& last){
lastName = last;
}
// get last name
std::string Employee::getLastName() const{
return lastName;
}
// set social security number
void Employee::setSocialSecurityNumber(const std::string& ssn){
socialSecurityNumber = ssn; // should validate
}
// get social security number
std::string Employee::getSocialSecurityNumber() const{
return socialSecurityNumber;
}
// set birthDate
void Employee::setBirthDate(int m, int d, int y){
birthDate = Date(m, d, y);
}
// get birthDate
Date Employee::getBirthDate() const{
return birthDate;
}
// Print Employee's information (virtual, but not pure virtual)
void Employee::print() const{
std::cout << getFirstName() << ' ' << getLastName()
<< "\nDate of birth: " << birthDate
<< "\nsocial security number: " << getSocialSecurityNumber();
}
// utility functions
bool Employee::isValidSocialSecurityNumber(const std::string& base) const{
for(size_t i=0; i<base.size(); ++i){
if(i == 3 || i == 6)
continue;
if(!isdigit(base[i]))
return false;
}
return true;
}
| [
"siidney.watson.work@gmail.com"
] | siidney.watson.work@gmail.com |
dfd4f132b8ecefefb3a86b9dab37fdaacdd6903f | a2c54f793b1b6858964e009e43be30dd5db8d55c | /GLProject/GLProject/Main.cpp | 766033940c007a2408d467d838a7282ffab35632 | [] | no_license | darkisu/GLProject | 745535c021580257cb473e33c57d81ba0f5a903a | 9e24a08562999e6b780c57017e68ebfb21597fae | refs/heads/master | 2020-12-24T07:41:23.179767 | 2017-07-10T16:46:55 | 2017-07-10T16:46:55 | 56,425,140 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 9,131 | cpp | #define _USE_MATH_DEFINES
#include <cmath>
// Custom Class Includes
#include "Scene.h"
#include "Camera.h"
#include "TextureShower.h"
#include "DeferredRenderer.h"
#include "ReflectiveShadowMap.h"
#include "LPV.h"
// GL Includes
#include <GLEW\glew.h>
#include <GLFW\glfw3.h>
#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <glm/gtc/type_ptr.hpp>
// window initiation
void initiate(int width, int height, string title);
// callbacks
void key_callback(GLFWwindow* window, int key, int scancode, int action, int mode);
void mouse_callback(GLFWwindow* window, double xpos, double ypos);
void scroll_callback(GLFWwindow* window, double xoffset, double yoffset);
void Do_Movement();
void Process_Light();
// Window
GLuint screenWidth = 1080;
GLuint screenHeight = 720;
// Display Object
GLFWwindow* pWindow;
// Camera
Camera camera(glm::vec3(0.0f, 0.0f, 0.0f));
bool keys[1024];
GLfloat lastX = 400, lastY = 300;
bool firstMouse = true;
GLfloat deltaTime = 0.0f;
GLfloat lastFrame = 0.0f;
// Point of Light
typedef struct
{
glm::vec3 position;
glm::vec3 color;
}PointOfLight;
// Point of Light
PointOfLight lightsource;
const float lightRange = 3064;
const float lightmovspeed = 0.01;
GLfloat lighttheta = 0, lightphi = M_PI / 2.0;
bool lightMoved = true;
// indirect settings;
int iterations = 5;
int main()
{
initiate( screenWidth, screenHeight,"GLProject Result");
// Scene ID Variables
GLuint sponzaID, cubeID;
// Scenes
Scene TargetScene(".\\model\\sponza.obj", sponzaID);
//Scene TargetScene(".\\model\\MyScene98.obj", sponzaID);
//TargetScene.loadModel(".\\model\\sponza.obj", cubeID);
//TargetScene.setModel(sponzaID, true, glm::vec3(0, 0, 0), glm::vec3(1.0, 1.0, 1.0));
//Scene TargetScene(".\\model\\san-miguel.obj",sponzaID);
// Shaders
Shader shader("./shader/defaultshader.glvs", "./shader/defaultshader.glfs",SHADER_FROM_FILE);
//Shader shader("./shader/deferredp1.glvs", "./shader/deferredp1.glfs", SHADER_FROM_FILE);
Shader showTexShader("./shader/showTexture.glvs", "./shader/showTexture.glfs", SHADER_FROM_FILE);
Shader RSMshader("./shader/RSM.glvs", "./shader/RSM.glfs", SHADER_FROM_FILE);
// Deferred Renderer
DeferredRenderer renderer(&TargetScene, screenWidth, screenHeight);
// Texture Shower
TextureShower textureShower;
textureShower.setTexture(renderer.diffuseTex);
// Reflective Shadow Map
ReflectiveShadowMap RSM(256,&TargetScene);
// Point of Light
lightsource.position = glm::vec3(0.0, lightRange, 0.0);
lightsource.color = glm::vec3(1, 1, 1);
//LPV
LPV lpv(&TargetScene, &RSM, 32);
//------Main Loop------//
while (!glfwWindowShouldClose(pWindow))
{
GLfloat currentFrameTime = glfwGetTime();
deltaTime = currentFrameTime - lastFrame;
lastFrame = currentFrameTime;
// Check and call events
glfwPollEvents();
Do_Movement();
Process_Light();
//RSM
RSM.draw(RSMshader, lightsource.position);
glViewport(0, 0, screenWidth, screenHeight);
//LPV
if (lightMoved)
{
lpv.gather();
lpv.inject(lightsource.position); // cause the slowing down of the rendering because of the loops in shader
lpv.propagate(iterations);
lightMoved = false;
}
// Clear the colorbuffer
glClearColor(0.15f, 0.15f, 0.15f, 1.0f);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glActiveTexture(GL_TEXTURE0);
// use shader
shader.Use();
// Camera setup
glViewport(0, 0, screenWidth, screenHeight);
glm::mat4 projection = glm::perspective(camera.Zoom, (float)screenWidth / (float)screenHeight, 1.0f, 10000.0f);
glm::mat4 view = camera.GetViewMatrix();
glm::mat4 VPMatrix = projection * view;
glUniformMatrix4fv(glGetUniformLocation(shader.Program, "VPMatrix"), 1, GL_FALSE, glm::value_ptr(VPMatrix));
glUniform3fv(glGetUniformLocation(shader.Program, "ViewPos"), 1, glm::value_ptr(camera.Position));
// Setup Light
glUniform3fv(glGetUniformLocation(shader.Program, "LightPos"), 1, glm::value_ptr(lightsource.position));
glUniform3fv(glGetUniformLocation(shader.Program, "LightColor"), 1, glm::value_ptr(lightsource.color));
glUniformMatrix4fv(glGetUniformLocation(shader.Program, "depthVP"), 1, GL_FALSE, glm::value_ptr(RSM.getShadowMappingMatrix() ));
// Shadow Texture
glActiveTexture(GL_TEXTURE1);
glBindTexture(GL_TEXTURE_2D, RSM.shadowMapTextureID);
glUniform1i(glGetUniformLocation(shader.Program, "depthTexture"), 1);
// LPV SHs
for (int i = 0; i < lpv.depth; i++)
{
glActiveTexture(GL_TEXTURE2 + i);
glBindTexture(GL_TEXTURE_3D, lpv.lightInfo3D[i]);
}
glUniform1i(glGetUniformLocation(shader.Program, "LPV00"), 2);
glUniform1i(glGetUniformLocation(shader.Program, "LPVn11"), 3);
glUniform1i(glGetUniformLocation(shader.Program, "LPV01"), 4);
glUniform1i(glGetUniformLocation(shader.Program, "LPVp11"), 5);
glUniform3fv(glGetUniformLocation(shader.Program, "lowerbound"), 1, glm::value_ptr(TargetScene.bCubeLower));
glUniform1f(glGetUniformLocation(shader.Program, "bboxlength"), TargetScene.bCubeLength);
glUniform1f(glGetUniformLocation(shader.Program, "LPVres"), lpv.resolution);
glUniform1f(glGetUniformLocation(shader.Program, "LPVsize"), lpv.LPVSize);
glUniform3fv(glGetUniformLocation(shader.Program, "eyepoint"), 1, glm::value_ptr(camera.Position));
// Draw the loaded model by deferred renderer
TargetScene.Draw(shader);
//renderer.drawP1(shader);
// Show Texture
//textureShower.setTexture(renderer.diffuseTex);
//textureShower.showTexture(showTexShader);
glBindTexture(GL_TEXTURE_2D, 0);
glfwSwapBuffers(pWindow);
}
return 0;
}
void initiate(int width, int height, string title)
{
//------GLFW Initiation------//
if (glfwInit() == false) {
cerr << "ERROR: GLFW initialization failed! -- (glfwinit)" << endl;
system("PAUSE");
glfwTerminate();
}
glfwWindowHint(GLFW_SAMPLES, 1);
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 4);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 4);
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
//------GLFW Window Creating------//
pWindow = glfwCreateWindow(width, height, title.c_str(), NULL, NULL);
if (pWindow == NULL)
{
cerr << "ERROR: Main window creation failed! -- (glfwCreateWindow)" << endl;
system("PAUSE");
glfwTerminate();
}
glfwMakeContextCurrent(pWindow);
//------GLFW Options------//
glfwSetInputMode(pWindow, GLFW_CURSOR, GLFW_CURSOR_DISABLED);
glfwSetKeyCallback(pWindow, key_callback);
glfwSetCursorPosCallback(pWindow, mouse_callback);
glfwSetScrollCallback(pWindow, scroll_callback);
//enable glew for newer version of open GL
glewExperimental = true;
if (glewInit() != GLEW_OK)
{
cerr << "ERROR: GLEW initialization failed! -- (glewInit)" << endl;
system("PAUSE");
}
//------Viewport Definition------//
glViewport(0, 0, width, height);
glEnable(GL_DEPTH_TEST);
glfwSwapInterval(0);
}
// Is called whenever a key is pressed/released via GLFW
void key_callback(GLFWwindow* window, int key, int scancode, int action, int mode)
{
if (key == GLFW_KEY_ESCAPE && action == GLFW_PRESS)
glfwSetWindowShouldClose(window, GL_TRUE);
if (action == GLFW_PRESS)
keys[key] = true;
else if (action == GLFW_RELEASE)
keys[key] = false;
}
void mouse_callback(GLFWwindow* window, double xpos, double ypos)
{
if (firstMouse)
{
lastX = xpos;
lastY = ypos;
firstMouse = false;
}
GLfloat xoffset = xpos - lastX;
GLfloat yoffset = lastY - ypos;
lastX = xpos;
lastY = ypos;
camera.ProcessMouseMovement(xoffset, yoffset);
}
void scroll_callback(GLFWwindow* window, double xoffset, double yoffset)
{
camera.ProcessMouseScroll(yoffset);
}
void Do_Movement()
{
// Camera controls
if (keys[GLFW_KEY_W])
camera.ProcessKeyboard(FORWARD, deltaTime);
if (keys[GLFW_KEY_S])
camera.ProcessKeyboard(BACKWARD, deltaTime);
if (keys[GLFW_KEY_A])
camera.ProcessKeyboard(LEFT, deltaTime);
if (keys[GLFW_KEY_D])
camera.ProcessKeyboard(RIGHT, deltaTime);
if (keys[GLFW_KEY_LEFT])
{
lighttheta -= lightmovspeed;
lightMoved = true;
}
if (keys[GLFW_KEY_RIGHT])
{
lighttheta += lightmovspeed;
lightMoved = true;
}
if (keys[GLFW_KEY_UP])
{
lightphi += lightmovspeed;
lightMoved = true;
}
if (keys[GLFW_KEY_DOWN])
{
lightphi -= lightmovspeed;
lightMoved = true;
}
//if (keys[GLFW_KEY_O])
//iterations++;
//if (keys[GLFW_KEY_P])
//iterations--;
}
void Process_Light()
{
lightphi = lightphi > M_PI / 2.0 ? M_PI / 2.0 : lightphi;
lightphi = lightphi < M_PI / 180 ? M_PI / 180 : lightphi;
lighttheta = lighttheta > 1.5*M_PI ? 1.5*M_PI : lighttheta;
lighttheta = lighttheta < 0.5*M_PI ? 0.5*M_PI : lighttheta;
lightsource.position.y = lightRange * sin(lightphi);
lightsource.position.x = lightRange * cos(lightphi) * cos(lighttheta);
lightsource.position.z = lightRange * cos(lightphi) * sin(lighttheta);
} | [
"darkisu@hotmail.com.tw"
] | darkisu@hotmail.com.tw |
282a9e8de7076a4dd120e453b55d06fc0e8cd13c | 2aecf6a8df0003d370a1854483d5a9069dc644f4 | /SecondSemester/Lab 1.5/TaskC/main.cpp | 136f87208261a51244a2ad718928ae92bb0ba71a | [] | no_license | Ckefy/Algorithm-and-data-structure | 9fe040f97813080ae4704669b4e36cec09c649dc | 8855787a21d3c0605ed0794e72139dcceb455e17 | refs/heads/master | 2020-12-10T19:26:41.836887 | 2020-01-13T20:53:56 | 2020-01-13T20:53:56 | 233,687,165 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,798 | cpp | #include <bits/stdc++.h>
#define ll int
using namespace std;
vector < pair < ll, pair < ll, ll > > > pool;
struct node {
node *l, *r, *parent;
ll key, prior, number;
node(){}
node (ll key, ll prior, ll number) : l(nullptr), r(nullptr), parent(nullptr), key (key), prior (prior), number (number){};
};
struct myType {
ll first, second, third;
myType(){}
myType (ll first, ll second, ll third) : first(first), second(second), third(third){};
};
vector <myType> answer;
node* root = nullptr;
pair < node*, node* > split (node* now, ll key){
if (now == nullptr){
return (make_pair(nullptr, nullptr));
} else if (key < now -> key){
pair < node*, node* > splited = split (now -> l, key);
now -> l = splited.second;
return (make_pair (splited.first, now));
} else {
pair < node*, node* > splited = split (now -> r, key);
now -> r = splited.first;
return (make_pair (now, splited.second));
}
}
node* merge (node* tree1, node* tree2){
if (tree1 == nullptr){
return tree2;
}
if (tree2 == nullptr){
return tree1;
}
if (tree1 -> prior < tree2 -> prior){
tree1 -> r = merge (tree1 -> r, tree2);
return tree1;
}
if (tree1 -> prior > tree2 -> prior){
tree2 -> l = merge (tree1, tree2 -> l);
return tree2;
}
}
node* insert (ll key, ll prior, ll number){
pair < node*, node* > splited = split (root, key);
node* newRoot = new node (key, prior, number);
newRoot = merge(splited.first, newRoot);
newRoot = merge (newRoot, splited.second);
return newRoot;
}
void printTree (node* cur, ll parent){
myType* nowAns = new myType (parent, ((cur -> l == nullptr) ? 0 : cur -> l -> number), ((cur -> r == nullptr) ? 0 : cur -> r -> number));
//cout<<nowAns -> first<<' '<<nowAns -> second<<' '<<nowAns -> third<<endl;
answer[cur -> number - 1] = *nowAns;
if (cur -> l != nullptr){
printTree (cur -> l, cur -> number);
}
if (cur -> r != nullptr){
printTree (cur -> r, cur -> number);
}
}
int main()
{
ios_base::sync_with_stdio(false);
cin.tie(NULL);
ll n;
cin>>n;
answer.resize(n);
for (int i = 0; i < n; i++){
pair < ll, pair < ll, ll > > now;
cin>>now.first;
cin>>now.second.first;
now.second.second = i + 1;
pool.push_back(now);
}
sort (pool.begin(), pool.end());
root = new node (pool[0].first, pool[0].second.first, pool[0].second.second);
node* previous = root;
for (int i = 1; i < n; i++){
bool flag = false;
int x = pool[i].first;
int y = pool[i].second.first;
if (previous -> prior < y){
previous -> r = new node (x, y, pool[i].second.second);
previous -> r -> parent = previous;
previous = previous -> r;
continue;
}
while (previous -> prior > y){
if (previous -> parent != nullptr){
previous = previous -> parent;
} else {
node* now = new node (x, y, pool[i].second.second);
now -> l = previous;
now -> l -> parent = now;
previous = now;
root = now;
flag = true;
break;
}
}
if (flag)
continue;
node* now = new node (x, y, pool[i].second.second);
now -> l = previous -> r;
now -> l -> parent = now;
now -> parent = previous;
previous -> r = now;
previous = now;
}
cout<<"YES"<<"\n";
printTree (root, 0);
for (int i = 0; i< n; i++){
cout<<answer[i].first<<' '<<answer[i].second<<' '<<answer[i].third<<"\n";
}
}
| [
"lukonin004@gmail.com"
] | lukonin004@gmail.com |
9db1a2c96bd4d1264d91ef758b4f64e7af4c32b7 | 99beb1671fb9be42eab32db26769dfd2e7edf883 | /PPD/exam-projects/BigNumbersMultiplication/BigNumbersMultiplication/BigNumbersMultiplication.cpp | 66de81bee749ae848bdc9d0bc956f532868fa3ec | [] | no_license | ioanajoj/Semester-5 | 079f072d71d38e4028320e1e94ceefeabc1dedcc | ab7385aad851e3dab19bcda6d73d3025d9521f99 | refs/heads/master | 2023-01-07T18:21:51.118180 | 2020-02-05T22:13:58 | 2020-02-05T22:13:58 | 216,260,489 | 1 | 1 | null | 2023-01-05T06:33:32 | 2019-10-19T19:36:13 | Java | UTF-8 | C++ | false | false | 1,691 | cpp | #include <iostream>
#include <fstream>
#include <vector>
#include <thread>
#include <mutex>
using namespace std;
mutex mtx;
vector< pair<int, int> > splitWorkload(int n, int t) {
vector< pair<int, int> > intervals;
int index = 0;
int step = n / t;
int mod = n % t;
while (index < n) {
intervals.push_back(pair<int, int>(index, index + step + (mod > 0)));
index += step + (mod > 0);
mod--;
}
return intervals;
}
inline vector <int> solve(vector <int> a, vector <int> b, int T) {
vector <int> res;
int n = a.size();
int m = 2 * n - 1;
res.resize(m, 0);
cout << m << endl;
vector< pair<int, int> > intervals = splitWorkload(2 * n - 1, T);
for (int i = 0; i < T; i++)
{
cout << intervals[i].first << ", " << intervals[i].second << endl;
}
vector <thread> thr;
for (int idx = 0; idx < T; ++idx) {
thr.push_back(thread([&, idx]() {
for (int x = intervals[idx].first; x < intervals[idx].second; x++) {
for (int i = 0; i < n; i++) {
if (x - i >= n || x - i < 0) {
continue;
}
res[x] += a[i] * b[x - i];
mtx.lock();
cout << "res[" << x << "] = a[" << i << "]*b[" << x - i << "]" << endl;
mtx.unlock();
}
}
}));
}
for (int i = 0; i < thr.size(); ++i) {
thr[i].join();
}
vector<int> result;
int carry = 0;
for (int i = res.size() - 1; i >= 0; i--)
{
res[i] += carry;
result.push_back(res[i] % 10);
if (res[i] > 9)
carry = res[i] / 10;
else
carry = 0;
}
while (carry > 0)
{
result.push_back(carry % 10);
carry /= 10;
}
reverse(result.begin(), result.end());
return result;
}
int main() {
for (auto it : solve({ 1, 2, 3, 4 }, { 5, 6, 7, 8 }, 3))
cout << it << " ";
cout << "\n";
} | [
"ioanna.gheorghiu@gmail.com"
] | ioanna.gheorghiu@gmail.com |
0e1eb86c85a4f4817d520339d800f280a3c04b0f | 4f91cb25e5bce06baeac70d0236e408a05608e5c | /C++/MP_V6/Application de gestion de rรฉservation du vol/ui_gestionvoyageur_dialog.h | dffb2e9b7034b240e66f148a8c3cb03867fae1c1 | [] | no_license | sabri97/ShareWorks | 6987f768f77dbffabe0af7be484e7ef76573abbe | f5023957e02f2ecaaef652852f14822fcd36aa7a | refs/heads/main | 2023-04-04T00:42:02.625791 | 2021-04-11T14:50:10 | 2021-04-11T14:50:10 | 348,349,126 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 11,613 | h | /********************************************************************************
** Form generated from reading UI file 'gestionvoyageur_dialog.ui'
**
** Created by: Qt User Interface Compiler version 5.2.0
**
** WARNING! All changes made in this file will be lost when recompiling UI file!
********************************************************************************/
#ifndef UI_GESTIONVOYAGEUR_DIALOG_H
#define UI_GESTIONVOYAGEUR_DIALOG_H
#include <QtCore/QVariant>
#include <QtWidgets/QAction>
#include <QtWidgets/QApplication>
#include <QtWidgets/QButtonGroup>
#include <QtWidgets/QDialog>
#include <QtWidgets/QHBoxLayout>
#include <QtWidgets/QHeaderView>
#include <QtWidgets/QLabel>
#include <QtWidgets/QLineEdit>
#include <QtWidgets/QPushButton>
#include <QtWidgets/QTableView>
#include <QtWidgets/QVBoxLayout>
#include <QtWidgets/QWidget>
QT_BEGIN_NAMESPACE
class Ui_GestionVoyageur_Dialog
{
public:
QLabel *label;
QTableView *tableView;
QWidget *layoutWidget_2;
QVBoxLayout *verticalLayout_4;
QHBoxLayout *horizontalLayout_5;
QPushButton *delete_2;
QPushButton *save;
QHBoxLayout *horizontalLayout_7;
QPushButton *load;
QPushButton *update;
QWidget *layoutWidget;
QHBoxLayout *horizontalLayout;
QVBoxLayout *verticalLayout_2;
QLabel *label_9;
QLabel *label_6;
QLabel *label_3;
QLabel *label_5;
QLabel *label_7;
QLabel *label_8;
QLabel *label_4;
QLabel *label_2;
QVBoxLayout *verticalLayout_3;
QLineEdit *txt_idVoyageur;
QHBoxLayout *horizontalLayout_4;
QLineEdit *txt_nom;
QLineEdit *txt_prenom;
QLineEdit *txt_nationalite;
QLineEdit *txt_telephone;
QLineEdit *txt_mail;
QLineEdit *txt_numPassport;
QHBoxLayout *horizontalLayout_6;
QLineEdit *txt_dateReservation;
QLineEdit *txt_heureReservation;
QLineEdit *txt_idVol;
void setupUi(QDialog *GestionVoyageur_Dialog)
{
if (GestionVoyageur_Dialog->objectName().isEmpty())
GestionVoyageur_Dialog->setObjectName(QStringLiteral("GestionVoyageur_Dialog"));
GestionVoyageur_Dialog->resize(787, 467);
label = new QLabel(GestionVoyageur_Dialog);
label->setObjectName(QStringLiteral("label"));
label->setGeometry(QRect(220, 9, 201, 31));
QFont font;
font.setFamily(QStringLiteral("Segoe UI"));
font.setPointSize(16);
label->setFont(font);
label->setLayoutDirection(Qt::LeftToRight);
label->setAlignment(Qt::AlignCenter);
tableView = new QTableView(GestionVoyageur_Dialog);
tableView->setObjectName(QStringLiteral("tableView"));
tableView->setGeometry(QRect(10, 280, 671, 150));
layoutWidget_2 = new QWidget(GestionVoyageur_Dialog);
layoutWidget_2->setObjectName(QStringLiteral("layoutWidget_2"));
layoutWidget_2->setGeometry(QRect(450, 90, 231, 130));
verticalLayout_4 = new QVBoxLayout(layoutWidget_2);
verticalLayout_4->setObjectName(QStringLiteral("verticalLayout_4"));
verticalLayout_4->setContentsMargins(0, 0, 0, 0);
horizontalLayout_5 = new QHBoxLayout();
horizontalLayout_5->setObjectName(QStringLiteral("horizontalLayout_5"));
delete_2 = new QPushButton(layoutWidget_2);
delete_2->setObjectName(QStringLiteral("delete_2"));
QFont font1;
font1.setFamily(QStringLiteral("Segoe UI"));
font1.setPointSize(10);
delete_2->setFont(font1);
QIcon icon;
icon.addFile(QStringLiteral("Data/Pictures/delete.png"), QSize(), QIcon::Normal, QIcon::Off);
delete_2->setIcon(icon);
delete_2->setIconSize(QSize(45, 45));
horizontalLayout_5->addWidget(delete_2);
save = new QPushButton(layoutWidget_2);
save->setObjectName(QStringLiteral("save"));
save->setFont(font1);
QIcon icon1;
icon1.addFile(QStringLiteral("Data/Pictures/save.png"), QSize(), QIcon::Normal, QIcon::Off);
save->setIcon(icon1);
save->setIconSize(QSize(45, 45));
horizontalLayout_5->addWidget(save);
verticalLayout_4->addLayout(horizontalLayout_5);
horizontalLayout_7 = new QHBoxLayout();
horizontalLayout_7->setObjectName(QStringLiteral("horizontalLayout_7"));
load = new QPushButton(layoutWidget_2);
load->setObjectName(QStringLiteral("load"));
QIcon icon2;
icon2.addFile(QStringLiteral("Data/Pictures/load.png"), QSize(), QIcon::Normal, QIcon::Off);
load->setIcon(icon2);
load->setIconSize(QSize(45, 45));
horizontalLayout_7->addWidget(load);
update = new QPushButton(layoutWidget_2);
update->setObjectName(QStringLiteral("update"));
update->setFont(font1);
QIcon icon3;
icon3.addFile(QStringLiteral("Data/Pictures/update.png"), QSize(), QIcon::Normal, QIcon::Off);
update->setIcon(icon3);
update->setIconSize(QSize(45, 45));
horizontalLayout_7->addWidget(update);
verticalLayout_4->addLayout(horizontalLayout_7);
layoutWidget = new QWidget(GestionVoyageur_Dialog);
layoutWidget->setObjectName(QStringLiteral("layoutWidget"));
layoutWidget->setGeometry(QRect(11, 61, 421, 210));
horizontalLayout = new QHBoxLayout(layoutWidget);
horizontalLayout->setObjectName(QStringLiteral("horizontalLayout"));
horizontalLayout->setContentsMargins(0, 0, 0, 0);
verticalLayout_2 = new QVBoxLayout();
verticalLayout_2->setObjectName(QStringLiteral("verticalLayout_2"));
label_9 = new QLabel(layoutWidget);
label_9->setObjectName(QStringLiteral("label_9"));
label_9->setFont(font1);
verticalLayout_2->addWidget(label_9);
label_6 = new QLabel(layoutWidget);
label_6->setObjectName(QStringLiteral("label_6"));
label_6->setFont(font1);
verticalLayout_2->addWidget(label_6);
label_3 = new QLabel(layoutWidget);
label_3->setObjectName(QStringLiteral("label_3"));
label_3->setFont(font1);
verticalLayout_2->addWidget(label_3);
label_5 = new QLabel(layoutWidget);
label_5->setObjectName(QStringLiteral("label_5"));
label_5->setFont(font1);
verticalLayout_2->addWidget(label_5);
label_7 = new QLabel(layoutWidget);
label_7->setObjectName(QStringLiteral("label_7"));
label_7->setFont(font1);
verticalLayout_2->addWidget(label_7);
label_8 = new QLabel(layoutWidget);
label_8->setObjectName(QStringLiteral("label_8"));
label_8->setFont(font1);
verticalLayout_2->addWidget(label_8);
label_4 = new QLabel(layoutWidget);
label_4->setObjectName(QStringLiteral("label_4"));
label_4->setFont(font1);
verticalLayout_2->addWidget(label_4);
label_2 = new QLabel(layoutWidget);
label_2->setObjectName(QStringLiteral("label_2"));
label_2->setFont(font1);
verticalLayout_2->addWidget(label_2);
horizontalLayout->addLayout(verticalLayout_2);
verticalLayout_3 = new QVBoxLayout();
verticalLayout_3->setObjectName(QStringLiteral("verticalLayout_3"));
txt_idVoyageur = new QLineEdit(layoutWidget);
txt_idVoyageur->setObjectName(QStringLiteral("txt_idVoyageur"));
txt_idVoyageur->setEnabled(false);
txt_idVoyageur->setReadOnly(true);
verticalLayout_3->addWidget(txt_idVoyageur);
horizontalLayout_4 = new QHBoxLayout();
horizontalLayout_4->setObjectName(QStringLiteral("horizontalLayout_4"));
txt_nom = new QLineEdit(layoutWidget);
txt_nom->setObjectName(QStringLiteral("txt_nom"));
horizontalLayout_4->addWidget(txt_nom);
txt_prenom = new QLineEdit(layoutWidget);
txt_prenom->setObjectName(QStringLiteral("txt_prenom"));
horizontalLayout_4->addWidget(txt_prenom);
verticalLayout_3->addLayout(horizontalLayout_4);
txt_nationalite = new QLineEdit(layoutWidget);
txt_nationalite->setObjectName(QStringLiteral("txt_nationalite"));
verticalLayout_3->addWidget(txt_nationalite);
txt_telephone = new QLineEdit(layoutWidget);
txt_telephone->setObjectName(QStringLiteral("txt_telephone"));
verticalLayout_3->addWidget(txt_telephone);
txt_mail = new QLineEdit(layoutWidget);
txt_mail->setObjectName(QStringLiteral("txt_mail"));
verticalLayout_3->addWidget(txt_mail);
txt_numPassport = new QLineEdit(layoutWidget);
txt_numPassport->setObjectName(QStringLiteral("txt_numPassport"));
verticalLayout_3->addWidget(txt_numPassport);
horizontalLayout_6 = new QHBoxLayout();
horizontalLayout_6->setObjectName(QStringLiteral("horizontalLayout_6"));
txt_dateReservation = new QLineEdit(layoutWidget);
txt_dateReservation->setObjectName(QStringLiteral("txt_dateReservation"));
txt_dateReservation->setEnabled(false);
txt_dateReservation->setAutoFillBackground(false);
txt_dateReservation->setReadOnly(false);
horizontalLayout_6->addWidget(txt_dateReservation);
txt_heureReservation = new QLineEdit(layoutWidget);
txt_heureReservation->setObjectName(QStringLiteral("txt_heureReservation"));
txt_heureReservation->setEnabled(false);
txt_heureReservation->setReadOnly(false);
horizontalLayout_6->addWidget(txt_heureReservation);
verticalLayout_3->addLayout(horizontalLayout_6);
txt_idVol = new QLineEdit(layoutWidget);
txt_idVol->setObjectName(QStringLiteral("txt_idVol"));
verticalLayout_3->addWidget(txt_idVol);
horizontalLayout->addLayout(verticalLayout_3);
retranslateUi(GestionVoyageur_Dialog);
QMetaObject::connectSlotsByName(GestionVoyageur_Dialog);
} // setupUi
void retranslateUi(QDialog *GestionVoyageur_Dialog)
{
GestionVoyageur_Dialog->setWindowTitle(QApplication::translate("GestionVoyageur_Dialog", "Dialog", 0));
label->setText(QApplication::translate("GestionVoyageur_Dialog", "Gestion de voyageur", 0));
delete_2->setText(QApplication::translate("GestionVoyageur_Dialog", "Delete", 0));
save->setText(QApplication::translate("GestionVoyageur_Dialog", "Save", 0));
load->setText(QApplication::translate("GestionVoyageur_Dialog", "Load", 0));
update->setText(QApplication::translate("GestionVoyageur_Dialog", "Update", 0));
label_9->setText(QApplication::translate("GestionVoyageur_Dialog", "ID Voyageur", 0));
label_6->setText(QApplication::translate("GestionVoyageur_Dialog", "Nom et Pr\303\251nom", 0));
label_3->setText(QApplication::translate("GestionVoyageur_Dialog", "Nationalit\303\251", 0));
label_5->setText(QApplication::translate("GestionVoyageur_Dialog", "Num\303\251ro de t\303\251l\303\251phone", 0));
label_7->setText(QApplication::translate("GestionVoyageur_Dialog", "E-mail", 0));
label_8->setText(QApplication::translate("GestionVoyageur_Dialog", "Num\303\251ro de passport", 0));
label_4->setText(QApplication::translate("GestionVoyageur_Dialog", "Date et heure de reservation", 0));
label_2->setText(QApplication::translate("GestionVoyageur_Dialog", "ID Vol", 0));
txt_telephone->setText(QString());
} // retranslateUi
};
namespace Ui {
class GestionVoyageur_Dialog: public Ui_GestionVoyageur_Dialog {};
} // namespace Ui
QT_END_NAMESPACE
#endif // UI_GESTIONVOYAGEUR_DIALOG_H
| [
"65515091+louaykaddoudi@users.noreply.github.com"
] | 65515091+louaykaddoudi@users.noreply.github.com |
4ff9230199b83924f7f2dc00a71ef21015bdbee9 | d6b4bdf418ae6ab89b721a79f198de812311c783 | /tke/include/tencentcloud/tke/v20180525/model/ECMRunMonitorServiceEnabled.h | d3658ad51e61957d67b80f3220bab91a5fc33fb8 | [
"Apache-2.0"
] | permissive | TencentCloud/tencentcloud-sdk-cpp-intl-en | d0781d461e84eb81775c2145bacae13084561c15 | d403a6b1cf3456322bbdfb462b63e77b1e71f3dc | refs/heads/master | 2023-08-21T12:29:54.125071 | 2023-08-21T01:12:39 | 2023-08-21T01:12:39 | 277,769,407 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,743 | h | /*
* Copyright (c) 2017-2019 THL A29 Limited, a Tencent company. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef TENCENTCLOUD_TKE_V20180525_MODEL_ECMRUNMONITORSERVICEENABLED_H_
#define TENCENTCLOUD_TKE_V20180525_MODEL_ECMRUNMONITORSERVICEENABLED_H_
#include <string>
#include <vector>
#include <map>
#include <tencentcloud/core/utils/rapidjson/document.h>
#include <tencentcloud/core/utils/rapidjson/writer.h>
#include <tencentcloud/core/utils/rapidjson/stringbuffer.h>
#include <tencentcloud/core/AbstractModel.h>
namespace TencentCloud
{
namespace Tke
{
namespace V20180525
{
namespace Model
{
/**
* ECM Cloud Monitoring
*/
class ECMRunMonitorServiceEnabled : public AbstractModel
{
public:
ECMRunMonitorServiceEnabled();
~ECMRunMonitorServiceEnabled() = default;
void ToJsonObject(rapidjson::Value &value, rapidjson::Document::AllocatorType& allocator) const;
CoreInternalOutcome Deserialize(const rapidjson::Value &value);
/**
* ่ทๅWhether it is enabled
* @return Enabled Whether it is enabled
*
*/
bool GetEnabled() const;
/**
* ่ฎพ็ฝฎWhether it is enabled
* @param _enabled Whether it is enabled
*
*/
void SetEnabled(const bool& _enabled);
/**
* ๅคๆญๅๆฐ Enabled ๆฏๅฆๅทฒ่ตๅผ
* @return Enabled ๆฏๅฆๅทฒ่ตๅผ
*
*/
bool EnabledHasBeenSet() const;
private:
/**
* Whether it is enabled
*/
bool m_enabled;
bool m_enabledHasBeenSet;
};
}
}
}
}
#endif // !TENCENTCLOUD_TKE_V20180525_MODEL_ECMRUNMONITORSERVICEENABLED_H_
| [
"tencentcloudapi@tencent.com"
] | tencentcloudapi@tencent.com |
5875b34bdac7ed08ecd41adc7a3fa88595335129 | d6670dc97e3d178668a30550d322e0efc52f2d97 | /facerecognitionlibrary/jni-build/jni/include/tensorflow/core/common_runtime/direct_session_test.cc | c8b8a09b8e86deacf161c4867ed6fcaf277df118 | [
"Apache-2.0",
"MIT",
"BSD-2-Clause-Views",
"BSD-3-Clause",
"LicenseRef-scancode-generic-cla",
"BSD-2-Clause"
] | permissive | ikaee/bfr-attendant | e31bc938aca1e247b05c369672cef0eda0fbbafe | 15e5a00d0dcb39b2903988658e3424b19bbc5a9f | refs/heads/master | 2022-12-23T22:05:23.132514 | 2017-05-14T10:56:02 | 2017-05-14T10:56:02 | 91,233,258 | 0 | 1 | Apache-2.0 | 2022-12-13T03:38:36 | 2017-05-14T09:33:29 | C++ | UTF-8 | C++ | false | false | 41,420 | cc | /* Copyright 2015 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include "tensorflow/core/common_runtime/direct_session.h"
#include <map>
#include <string>
#include <unordered_map>
#include <vector>
#include "tensorflow/core/common_runtime/device_factory.h"
#include "tensorflow/core/framework/allocator.h"
#include "tensorflow/core/framework/graph.pb.h"
#include "tensorflow/core/framework/op_kernel.h"
#include "tensorflow/core/framework/tensor.h"
#include "tensorflow/core/framework/tensor_testutil.h"
#include "tensorflow/core/framework/types.pb.h"
#include "tensorflow/core/graph/costmodel.h"
#include "tensorflow/core/graph/graph.h"
#include "tensorflow/core/graph/node_builder.h"
#include "tensorflow/core/graph/testlib.h"
#include "tensorflow/core/kernels/ops_util.h"
#include "tensorflow/core/lib/core/errors.h"
#include "tensorflow/core/lib/core/status.h"
#include "tensorflow/core/lib/core/status_test_util.h"
#include "tensorflow/core/lib/core/threadpool.h"
#include "tensorflow/core/platform/test.h"
#include "tensorflow/core/platform/test_benchmark.h"
#include "tensorflow/core/public/session.h"
#include "tensorflow/core/public/session_options.h"
#include "tensorflow/core/util/device_name_utils.h"
namespace tensorflow {
namespace {
Session* CreateSession() {
SessionOptions options;
(*options.config.mutable_device_count())["CPU"] = 2;
return NewSession(options);
}
class DirectSessionMinusAXTest : public ::testing::Test {
public:
void Initialize(std::initializer_list<float> a_values) {
Graph graph(OpRegistry::Global());
Tensor a_tensor(DT_FLOAT, TensorShape({2, 2}));
test::FillValues<float>(&a_tensor, a_values);
Node* a = test::graph::Constant(&graph, a_tensor);
a->set_assigned_device_name("/job:localhost/replica:0/task:0/cpu:0");
Tensor x_tensor(DT_FLOAT, TensorShape({2, 1}));
test::FillValues<float>(&x_tensor, {1, 1});
Node* x = test::graph::Constant(&graph, x_tensor);
x->set_assigned_device_name("/job:localhost/replica:0/task:0/cpu:1");
x_ = x->name();
// y = A * x
Node* y = test::graph::Matmul(&graph, a, x, false, false);
y->set_assigned_device_name("/job:localhost/replica:0/task:0/cpu:0");
y_ = y->name();
Node* y_neg = test::graph::Unary(&graph, "Neg", y);
y_neg_ = y_neg->name();
y_neg->set_assigned_device_name("/job:localhost/replica:0/task:0/cpu:1");
test::graph::ToGraphDef(&graph, &def_);
}
string x_;
string y_;
string y_neg_;
GraphDef def_;
};
TEST_F(DirectSessionMinusAXTest, RunSimpleNetwork) {
Initialize({3, 2, -1, 0});
std::unique_ptr<Session> session(CreateSession());
ASSERT_TRUE(session != nullptr);
TF_ASSERT_OK(session->Create(def_));
std::vector<std::pair<string, Tensor>> inputs;
// Request two targets: one fetch output and one non-fetched output.
std::vector<string> output_names = {y_ + ":0"};
std::vector<string> target_nodes = {y_neg_};
std::vector<Tensor> outputs;
Status s = session->Run(inputs, output_names, target_nodes, &outputs);
TF_ASSERT_OK(s);
ASSERT_EQ(1, outputs.size());
// The first output should be initialized and have the correct
// output.
auto mat = outputs[0].matrix<float>();
ASSERT_TRUE(outputs[0].IsInitialized());
EXPECT_FLOAT_EQ(5.0, mat(0, 0));
}
TEST_F(DirectSessionMinusAXTest, TestFeed) {
Initialize({1, 2, 3, 4});
std::unique_ptr<Session> session(CreateSession());
ASSERT_TRUE(session != nullptr);
TF_ASSERT_OK(session->Create(def_));
// Fill in the input and ask for the output
//
// Note that the input being fed is on the second device.
Tensor t(DT_FLOAT, TensorShape({2, 1}));
t.matrix<float>()(0, 0) = 5;
t.matrix<float>()(1, 0) = 6;
std::vector<std::pair<string, Tensor>> inputs = {{x_, t}};
std::vector<string> output_names = {y_ + ":0"};
std::vector<Tensor> outputs;
// Run the graph
Status s = session->Run(inputs, output_names, {}, &outputs);
TF_ASSERT_OK(s);
ASSERT_EQ(1, outputs.size());
auto mat = outputs[0].matrix<float>();
// Expect outputs to be; 1*5 + 2*6, 3*5 + 4*6
EXPECT_FLOAT_EQ(17.0, mat(0, 0));
EXPECT_FLOAT_EQ(39.0, mat(1, 0));
}
TEST_F(DirectSessionMinusAXTest, TestConcurrency) {
Initialize({1, 2, 3, 4});
std::unique_ptr<Session> session(CreateSession());
ASSERT_TRUE(session != nullptr);
TF_ASSERT_OK(session->Create(def_));
// Fill in the input and ask for the output
thread::ThreadPool* tp = new thread::ThreadPool(Env::Default(), "test", 4);
// Run the graph 1000 times in 4 different threads concurrently.
std::vector<string> output_names = {y_ + ":0"};
auto fn = [&session, output_names]() {
for (int i = 0; i < 1000; ++i) {
std::vector<std::pair<string, Tensor>> inputs;
std::vector<Tensor> outputs;
// Run the graph
Status s = session->Run(inputs, output_names, {}, &outputs);
TF_ASSERT_OK(s);
ASSERT_EQ(1, outputs.size());
auto mat = outputs[0].matrix<float>();
EXPECT_FLOAT_EQ(3.0, mat(0, 0));
}
};
for (int i = 0; i < 4; ++i) {
tp->Schedule(fn);
}
// Wait for the functions to finish.
delete tp;
}
TEST_F(DirectSessionMinusAXTest, TestPerSessionThreads) {
Initialize({1, 2, 3, 4});
SessionOptions options;
options.config.set_use_per_session_threads(true);
(*options.config.mutable_device_count())["CPU"] = 2;
std::unique_ptr<Session> session(NewSession(options));
ASSERT_TRUE(session != nullptr);
TF_ASSERT_OK(session->Create(def_));
// Fill in the input and ask for the output
thread::ThreadPool* tp = new thread::ThreadPool(Env::Default(), "test", 4);
// Run the graph 1000 times in 4 different threads concurrently.
std::vector<string> output_names = {y_ + ":0"};
auto fn = [&session, output_names]() {
for (int i = 0; i < 1000; ++i) {
std::vector<std::pair<string, Tensor>> inputs;
std::vector<Tensor> outputs;
// Run the graph
Status s = session->Run(inputs, output_names, {}, &outputs);
TF_ASSERT_OK(s);
ASSERT_EQ(1, outputs.size());
auto mat = outputs[0].matrix<float>();
EXPECT_FLOAT_EQ(3.0, mat(0, 0));
}
};
for (int i = 0; i < 4; ++i) {
tp->Schedule(fn);
}
// Wait for the functions to finish.
delete tp;
}
TEST_F(DirectSessionMinusAXTest, TwoCreateCallsFails) {
Initialize({1, 2, 3, 4});
std::unique_ptr<Session> session(CreateSession());
ASSERT_TRUE(session != nullptr);
TF_ASSERT_OK(session->Create(def_));
// Second is not.
ASSERT_FALSE(session->Create(def_).ok());
}
TEST_F(DirectSessionMinusAXTest, ForgetToCreate) {
Initialize({1, 2, 3, 4});
std::unique_ptr<Session> session(CreateSession());
ASSERT_TRUE(session != nullptr);
std::vector<std::pair<string, Tensor>> inputs;
std::vector<Tensor> outputs;
ASSERT_FALSE(session->Run(inputs, {y_ + ":0"}, {y_neg_}, &outputs).ok());
}
TEST_F(DirectSessionMinusAXTest, InvalidDevice) {
GraphDef def;
Graph graph(OpRegistry::Global());
Tensor a_tensor(DT_FLOAT, TensorShape({2, 2}));
a_tensor.flat<float>().setRandom();
Node* a = test::graph::Constant(&graph, a_tensor);
a->set_assigned_device_name("/job:localhost/replica:0/task:0/cpu:0");
Tensor x_tensor(DT_FLOAT, TensorShape({2, 1}));
x_tensor.flat<float>().setRandom();
Node* x = test::graph::Constant(&graph, x_tensor);
x->set_assigned_device_name("/job:localhost/replica:0/task:0/cpu:1");
// Skip placing y.
Node* y = test::graph::Matmul(&graph, a, x, false, false);
y->set_assigned_device_name("/job:localhost/replica:0/task:0/cpu:2");
test::graph::ToGraphDef(&graph, &def);
SessionOptions options;
(*options.config.mutable_device_count())["CPU"] = 2;
std::unique_ptr<Session> session(NewSession(options));
ASSERT_TRUE(session != nullptr);
// Should return an error.
ASSERT_FALSE(session->Create(def).ok());
// Fix placement and run again
def.Clear();
y->set_assigned_device_name("/job:localhost/replica:0/task:0/cpu:1");
test::graph::ToGraphDef(&graph, &def);
session.reset(NewSession(options));
TF_ASSERT_OK(session->Create(def));
std::vector<Tensor> outputs;
TF_ASSERT_OK(session->Run({}, {y->name() + ":0"}, {}, &outputs));
}
TEST_F(DirectSessionMinusAXTest, RunSimpleNetworkWithOpts) {
Initialize({3, 2, -1, 0});
std::unique_ptr<Session> session(CreateSession());
ASSERT_TRUE(session != nullptr);
TF_ASSERT_OK(session->Create(def_));
std::vector<std::pair<string, Tensor>> inputs;
// Request two targets: one fetch output and one non-fetched output.
std::vector<string> output_names = {y_ + ":0"};
std::vector<string> target_nodes = {y_neg_};
std::vector<Tensor> outputs;
// Prepares RunOptions and RunMetadata
RunOptions run_options;
run_options.set_trace_level(RunOptions::FULL_TRACE);
RunMetadata run_metadata;
EXPECT_EQ(run_metadata.step_stats().dev_stats_size(), 0);
Status s = session->Run(run_options, inputs, output_names, target_nodes,
&outputs, &run_metadata);
TF_ASSERT_OK(s);
ASSERT_EQ(1, outputs.size());
// The first output should be initialized and have the correct
// output.
auto mat = outputs[0].matrix<float>();
ASSERT_TRUE(outputs[0].IsInitialized());
EXPECT_FLOAT_EQ(5.0, mat(0, 0));
// Checks RunMetadata is well-formed
ASSERT_TRUE(run_metadata.has_step_stats());
EXPECT_EQ(run_metadata.step_stats().dev_stats_size(), 2);
}
TEST(DirectSessionTest, KeepsStateAcrossRunsOfSession) {
GraphDef def;
Graph g(OpRegistry::Global());
Node* var = test::graph::Var(&g, DT_FLOAT, TensorShape({10}));
var->set_assigned_device_name("/job:localhost/replica:0/task:0/cpu:0");
Tensor twenty(DT_FLOAT, TensorShape({10}));
for (int i = 0; i < 10; ++i) {
twenty.flat<float>()(i) = 20.0;
}
Node* twenty_node = test::graph::Constant(&g, twenty);
twenty_node->set_assigned_device_name(
"/job:localhost/replica:0/task:0/cpu:0");
Node* init = test::graph::Assign(&g, var, twenty_node);
init->set_assigned_device_name("/job:localhost/replica:0/task:0/cpu:0");
test::graph::ToGraphDef(&g, &def);
std::unique_ptr<Session> session(CreateSession());
ASSERT_TRUE(session != nullptr);
TF_ASSERT_OK(session->Create(def));
std::vector<std::pair<string, Tensor>> inputs;
std::vector<Tensor> outputs;
// Initialize the variable
Status s = session->Run(inputs, {init->name()}, {}, &outputs);
TF_ASSERT_OK(s);
// Get the variable's data
s = session->Run(inputs, {var->name() + ":0"}, {}, &outputs);
TF_ASSERT_OK(s);
ASSERT_EQ(1, outputs.size());
ASSERT_TRUE(outputs[0].IsInitialized());
EXPECT_EQ(20.0, outputs[0].flat<float>()(0));
}
TEST(DirectSessionTest, MultipleFeedTest) {
GraphDef def;
Graph g(OpRegistry::Global());
Tensor first_value(DT_FLOAT, TensorShape({}));
first_value.scalar<float>()() = 1.0;
Node* first_const = test::graph::Constant(&g, first_value);
Node* first_identity = test::graph::Identity(&g, first_const);
Tensor second_value(DT_FLOAT, TensorShape({}));
second_value.scalar<float>()() = 2.0;
Node* second_const = test::graph::Constant(&g, second_value);
Node* second_identity = test::graph::Identity(&g, second_const);
test::graph::ToGraphDef(&g, &def);
std::unique_ptr<Session> session(CreateSession());
ASSERT_TRUE(session != nullptr);
TF_ASSERT_OK(session->Create(def));
std::vector<Tensor> outputs;
// Fetch without feeding.
Status s = session->Run(
{}, {first_identity->name() + ":0", second_identity->name() + ":0"}, {},
&outputs);
TF_ASSERT_OK(s);
ASSERT_EQ(2, outputs.size());
ASSERT_EQ(1.0, outputs[0].flat<float>()(0));
ASSERT_EQ(2.0, outputs[1].flat<float>()(0));
s = session->Run(
{}, {second_identity->name() + ":0", first_identity->name() + ":0"}, {},
&outputs);
TF_ASSERT_OK(s);
ASSERT_EQ(2, outputs.size());
ASSERT_EQ(2.0, outputs[0].flat<float>()(0));
ASSERT_EQ(1.0, outputs[1].flat<float>()(0));
Tensor value_11(DT_FLOAT, TensorShape({}));
value_11.scalar<float>()() = 11.0;
Tensor value_22(DT_FLOAT, TensorShape({}));
value_22.scalar<float>()() = 22.0;
// Feed [first_const, second_const]
s = session->Run(
{{first_const->name(), value_11}, {second_const->name(), value_22}},
{first_identity->name() + ":0", second_identity->name() + ":0"}, {},
&outputs);
TF_ASSERT_OK(s);
ASSERT_EQ(2, outputs.size());
ASSERT_EQ(11.0, outputs[0].flat<float>()(0));
ASSERT_EQ(22.0, outputs[1].flat<float>()(0));
// Feed [second_const, first_const]
s = session->Run(
{{second_const->name(), value_22}, {first_const->name(), value_11}},
{first_identity->name() + ":0", second_identity->name() + ":0"}, {},
&outputs);
TF_ASSERT_OK(s);
ASSERT_EQ(2, outputs.size());
ASSERT_EQ(11.0, outputs[0].flat<float>()(0));
ASSERT_EQ(22.0, outputs[1].flat<float>()(0));
// Feed [first_const, first_const]
s = session->Run(
{{first_const->name(), value_11}, {first_const->name(), value_22}},
{first_identity->name() + ":0", second_identity->name() + ":0"}, {},
&outputs);
EXPECT_TRUE(errors::IsInvalidArgument(s));
EXPECT_TRUE(StringPiece(s.error_message()).contains("fed more than once"));
}
REGISTER_OP("Darth")
.Input("x: float")
.Output("y: float")
.Doc(R"doc(
Darth promises one return value.
x: float
y: float
)doc");
// The DarthOp kernel violates its promise to return one-value.
class DarthOp : public OpKernel {
public:
explicit DarthOp(OpKernelConstruction* ctx) : OpKernel(ctx) {}
void Compute(OpKernelContext* ctx) override {}
};
REGISTER_KERNEL_BUILDER(Name("Darth").Device(DEVICE_CPU), DarthOp);
TEST(DirectSessionTest, DarthKernel) {
Graph g(OpRegistry::Global());
Tensor vx(DT_FLOAT, TensorShape({}));
vx.scalar<float>()() = 1.0;
Node* x = test::graph::Constant(&g, vx);
Node* y = test::graph::Unary(&g, "Darth", x);
GraphDef def;
test::graph::ToGraphDef(&g, &def);
auto sess = CreateSession();
TF_ASSERT_OK(sess->Create(def));
std::vector<Tensor> outputs;
auto s = sess->Run({}, {y->name() + ":0"}, {}, &outputs);
EXPECT_TRUE(errors::IsInternal(s));
delete sess;
}
// Have the Darth op in the graph placed on GPU, but don't run it.
TEST(DirectSessionTest, PlacePrunedGraph) {
{
Graph g(OpRegistry::Global());
Tensor vx(DT_FLOAT, TensorShape({}));
vx.scalar<float>()() = 1.0;
Node* x = test::graph::Constant(&g, vx);
Node* y = test::graph::Unary(&g, "Darth", x);
y->set_assigned_device_name("/job:localhost/replica:0/task:0/gpu:0");
GraphDef def;
test::graph::ToGraphDef(&g, &def);
// By default, we place the entire graph, so we should fail the
// call to Create.
SessionOptions options;
std::unique_ptr<Session> sess(NewSession(options));
auto s = sess->Create(def);
EXPECT_TRUE(errors::IsInvalidArgument(s));
}
{
Graph g(OpRegistry::Global());
Tensor vx(DT_FLOAT, TensorShape({}));
vx.scalar<float>()() = 1.0;
Node* x = test::graph::Constant(&g, vx);
Node* y = test::graph::Unary(&g, "Darth", x);
y->set_assigned_device_name("/job:localhost/replica:0/task:0/gpu:0");
GraphDef def;
test::graph::ToGraphDef(&g, &def);
SessionOptions options;
// Set the option to place pruned graphs, we should expect this
// to run.
options.config.mutable_graph_options()->set_place_pruned_graph(true);
std::unique_ptr<Session> sess(NewSession(options));
TF_ASSERT_OK(sess->Create(def));
std::vector<Tensor> outputs;
auto s = sess->Run({}, {x->name() + ":0"}, {}, &outputs);
TF_EXPECT_OK(s);
}
}
TEST(DirectSessionTest, PartialRunTest) {
GraphDef def;
Graph g(OpRegistry::Global());
Tensor first_value(DT_FLOAT, TensorShape({}));
first_value.scalar<float>()() = 1.0;
Node* first_const = test::graph::Constant(&g, first_value);
Node* first_identity = test::graph::Identity(&g, first_const);
Tensor second_value(DT_FLOAT, TensorShape({}));
second_value.scalar<float>()() = 2.0;
Node* second_const = test::graph::Constant(&g, second_value);
Node* second_identity = test::graph::Identity(&g, second_const);
Node* third = test::graph::Add(&g, first_identity, second_identity);
Node* third_identity = test::graph::Identity(&g, third);
test::graph::ToGraphDef(&g, &def);
std::unique_ptr<Session> session(CreateSession());
ASSERT_TRUE(session != nullptr);
TF_ASSERT_OK(session->Create(def));
std::vector<Tensor> outputs;
string handle;
Status s = session->PRunSetup(
{first_const->name(), second_const->name()},
{first_identity->name() + ":0", second_identity->name() + ":0",
third_identity->name() + ":0"},
{}, &handle);
TF_ASSERT_OK(s);
Tensor value_11(DT_FLOAT, TensorShape({}));
value_11.scalar<float>()() = 11.0;
Tensor value_22(DT_FLOAT, TensorShape({}));
value_22.scalar<float>()() = 22.0;
// Feed first_const, fetch first_identity
s = session->PRun(handle, {{first_const->name(), value_11}},
{first_identity->name() + ":0"}, &outputs);
TF_ASSERT_OK(s);
ASSERT_EQ(1, outputs.size());
ASSERT_EQ(11.0, outputs[0].flat<float>()(0));
// Feed second_const, fetch second_identity and third_identity
s = session->PRun(
handle, {{second_const->name(), value_22}},
{second_identity->name() + ":0", third_identity->name() + ":0"},
&outputs);
TF_ASSERT_OK(s);
ASSERT_EQ(2, outputs.size());
ASSERT_EQ(22.0, outputs[0].flat<float>()(0));
ASSERT_EQ(11.0 + 22.0, outputs[1].flat<float>()(0));
}
TEST(DirectSessionTest, PartialRunMissingFeed) {
GraphDef def;
Graph g(OpRegistry::Global());
Tensor first_value(DT_FLOAT, TensorShape({}));
first_value.scalar<float>()() = 1.0;
Node* first_const = test::graph::Constant(&g, first_value);
Node* first_identity = test::graph::Identity(&g, first_const);
Tensor second_value(DT_FLOAT, TensorShape({}));
second_value.scalar<float>()() = 2.0;
Node* second_const = test::graph::Constant(&g, second_value);
Node* second_identity = test::graph::Identity(&g, second_const);
Node* third = test::graph::Add(&g, first_identity, second_identity);
Node* third_identity = test::graph::Identity(&g, third);
test::graph::ToGraphDef(&g, &def);
std::unique_ptr<Session> session(CreateSession());
ASSERT_TRUE(session != nullptr);
TF_ASSERT_OK(session->Create(def));
std::vector<Tensor> outputs;
string handle;
Status s = session->PRunSetup({first_const->name(), second_const->name()},
{third_identity->name() + ":0"}, {}, &handle);
TF_ASSERT_OK(s);
// Feed first_const, fetch third_identity
Tensor value_11(DT_FLOAT, TensorShape({}));
value_11.scalar<float>()() = 11.0;
s = session->PRun(handle, {{first_const->name(), value_11}},
{third_identity->name() + ":0"}, &outputs);
ASSERT_TRUE(errors::IsInvalidArgument(s));
EXPECT_TRUE(StringPiece(s.error_message())
.contains("can't be computed from the feeds"));
}
TEST(DirectSessionTest, PartialRunMultiOutputFeed) {
GraphDef def;
Graph g(OpRegistry::Global());
Tensor bool_value(DT_BOOL, TensorShape({}));
bool_value.scalar<bool>()() = true;
Node* bool_const = test::graph::Constant(&g, bool_value);
Node* switch_node = test::graph::Switch(&g, bool_const, bool_const);
Node* fourth_identity = test::graph::Identity(&g, switch_node, 1);
test::graph::ToGraphDef(&g, &def);
std::unique_ptr<Session> session(CreateSession());
ASSERT_TRUE(session != nullptr);
TF_ASSERT_OK(session->Create(def));
std::vector<Tensor> outputs;
string handle;
Status s = session->PRunSetup({switch_node->name() + ":1"},
{fourth_identity->name() + ":0"}, {}, &handle);
TF_ASSERT_OK(s);
// Fetch fourth_identity without feeds.
s = session->PRun(handle, {}, {fourth_identity->name() + ":0"}, &outputs);
ASSERT_TRUE(errors::IsInvalidArgument(s));
EXPECT_TRUE(StringPiece(s.error_message())
.contains("can't be computed from the feeds"));
// Feed switch_node:1 and fetch fourth_identity.
s = session->PRun(handle, {{switch_node->name() + ":1", bool_value}},
{fourth_identity->name() + ":0"}, &outputs);
TF_ASSERT_OK(s);
ASSERT_EQ(1, outputs.size());
ASSERT_EQ(true, outputs[0].flat<bool>()(0));
}
TEST(DirectSessionTest, RunHandleTest) {
GraphDef def;
Graph g(OpRegistry::Global());
Tensor value0(DT_FLOAT, TensorShape({}));
value0.scalar<float>()() = 1.0;
Node* const0 = test::graph::Constant(&g, value0);
Node* identity0 = test::graph::Identity(&g, const0);
Tensor value1(DT_FLOAT, TensorShape({}));
value1.scalar<float>()() = 2.0;
Node* const1 = test::graph::Constant(&g, value1);
Node* node3 = test::graph::Add(&g, identity0, const1);
Node* node4 = test::graph::Unary(&g, "GetSessionHandleV2", node3);
Tensor value2(DT_STRING, TensorShape({}));
Node* const2 = test::graph::Constant(&g, value2);
Node* node5 = test::graph::GetSessionTensor(&g, const2);
Node* node6 = test::graph::Add(&g, node5, const1);
Node* node7 = test::graph::Unary(&g, "DeleteSessionTensor", const2);
test::graph::ToGraphDef(&g, &def);
std::unique_ptr<Session> session(CreateSession());
ASSERT_TRUE(session != nullptr);
TF_ASSERT_OK(session->Create(def));
// First run call: Create a handle.
std::vector<Tensor> outputs;
Status s = session->Run({}, {node4->name() + ":0"}, {}, &outputs);
ASSERT_TRUE(s.ok());
ASSERT_EQ(1, outputs.size());
ResourceHandle resource_handle = outputs[0].scalar<ResourceHandle>()();
Tensor string_handle(DT_STRING, {});
string_handle.flat<string>().setConstant(resource_handle.name());
// Second run call: Use a handle.
std::vector<Tensor> outputs1;
s = session->Run({{const2->name(), string_handle}}, {node6->name() + ":0"},
{}, &outputs1);
ASSERT_TRUE(s.ok());
ASSERT_EQ(1, outputs1.size());
ASSERT_EQ(5.0, outputs1[0].flat<float>()(0));
// Third run call: Delete a handle.
std::vector<Tensor> outputs2;
s = session->Run({{const2->name(), string_handle}}, {}, {node7->name()},
&outputs2);
ASSERT_TRUE(s.ok());
}
TEST(DirectSessionTest, CreateGraphFailsWhenAssigningAFedVar) {
Graph graph(OpRegistry::Global());
Node* a = test::graph::Var(&graph, DT_FLOAT, {});
Node* b = test::graph::Constant(&graph, {});
Tensor zero(DT_FLOAT, {});
test::FillValues<float>(&zero, {0});
// a = b
Node* assign = test::graph::Assign(&graph, a, b);
std::unique_ptr<Session> session(CreateSession());
ASSERT_TRUE(session != nullptr);
// The graph is invalid since a constant cannot be assigned to a constant.
// The return Status of session->Run should flag this as an invalid argument.
std::vector<Tensor> outputs;
Status s = session->Run({{a->name(), zero}}, {assign->name()}, {}, &outputs);
ASSERT_TRUE(errors::IsInvalidArgument(s));
}
TEST(DirectSessionTest, TimeoutSession) {
GraphDef graph;
// Creates a graph with one FIFOQueue and one dequeue op.
protobuf::TextFormat::ParseFromString(R"proto(
node {
name: 'fifo_queue'
op: 'FIFOQueue'
device: '/device:CPU:0'
attr {
key: 'capacity'
value {
i: 10
}
}
attr {
key: 'component_types'
value {
list {
type: DT_FLOAT
}
}
}
attr {
key: 'container'
value {
s: ''
}
}
attr {
key: 'shapes'
value {
list {
}
}
}
attr {
key: 'shared_name'
value {
s: ''
}
}
}
node {
name: 'fifo_queue_Dequeue'
op: 'QueueDequeue'
input: 'fifo_queue'
device: '/device:CPU:0'
attr {
key: 'component_types'
value {
list {
type: DT_FLOAT
}
}
}
attr {
key: 'timeout_ms'
value {
i: -1
}
}
}
versions {
producer: 9
}
)proto",
&graph);
// Creates a session with operation_timeout_in_ms set to 100 milliseconds.
SessionOptions options;
(*options.config.mutable_device_count())["CPU"] = 2;
options.config.set_operation_timeout_in_ms(100);
std::unique_ptr<Session> session(NewSession(options));
ASSERT_TRUE(session != nullptr);
TF_ASSERT_OK(session->Create(graph));
// Verifies that the error code is DEADLINE_EXCEEDED.
Status s = session->Run({}, {}, {"fifo_queue_Dequeue"}, nullptr);
ASSERT_EQ(error::DEADLINE_EXCEEDED, s.code());
TF_ASSERT_OK(session->Close());
// Creates a session with no operation_timeout_in_ms.
session.reset(CreateSession());
ASSERT_TRUE(session != nullptr);
TF_ASSERT_OK(session->Create(graph));
RunOptions run_options;
run_options.set_timeout_in_ms(20);
// Verifies that the error code is DEADLINE_EXCEEDED.
Status s2 = session->Run(run_options, {}, {}, {"fifo_queue_Dequeue"}, nullptr,
nullptr);
ASSERT_EQ(error::DEADLINE_EXCEEDED, s2.code());
TF_ASSERT_OK(session->Close());
}
// Accesses the cancellation manager for the step after the step has been
// cancelled.
class CancellationMgrPollingOp : public OpKernel {
public:
explicit CancellationMgrPollingOp(OpKernelConstruction* ctx)
: OpKernel(ctx) {}
void Compute(OpKernelContext* ctx) override {
CancellationManager* cm = ctx->cancellation_manager();
while (!cm->IsCancelled()) {
ctx->env()->SleepForMicroseconds(1000);
}
notification.Notify();
}
static Notification notification;
};
Notification CancellationMgrPollingOp::notification;
REGISTER_KERNEL_BUILDER(Name("CancellationMgrPollingOp").Device(DEVICE_CPU),
CancellationMgrPollingOp);
REGISTER_OP("CancellationMgrPollingOp").Doc("");
TEST(DirectSessionTest, TestTimeoutCleanShutdown) {
GraphDef graph;
// Creates a graph with one FIFOQueue and one dequeue op.
protobuf::TextFormat::ParseFromString(R"proto(
node {
name: 'cm_polling'
op: 'CancellationMgrPollingOp'
device: '/device:CPU:0'
}
versions {
producer: 9
}
)proto",
&graph);
// Creates a session with operation_timeout_in_ms set to 100 milliseconds.
SessionOptions options;
options.config.set_operation_timeout_in_ms(100);
std::unique_ptr<Session> session(NewSession(options));
ASSERT_TRUE(session != nullptr);
TF_ASSERT_OK(session->Create(graph));
// Verifies that the error code is DEADLINE_EXCEEDED.
Status s = session->Run({}, {}, {"cm_polling"}, nullptr);
ASSERT_EQ(error::DEADLINE_EXCEEDED, s.code());
// Verify that the op ran to completion.
ASSERT_TRUE(CancellationMgrPollingOp::notification.HasBeenNotified());
TF_ASSERT_OK(session->Close());
}
class BlockingOpState {
public:
void AwaitState(int awaiting_state) {
mutex_lock ml(mu_);
while (state_ != awaiting_state) {
cv_.wait(ml);
}
}
void MoveToState(int expected_current, int next) {
mutex_lock ml(mu_);
CHECK_EQ(expected_current, state_);
state_ = next;
cv_.notify_all();
}
private:
mutex mu_;
condition_variable cv_;
int state_ = 0;
};
static BlockingOpState* blocking_op_state = nullptr;
// BlockingOp blocks on the global <blocking_op_state's> state,
// and also updates it when it is unblocked and finishing computation.
class BlockingOp : public OpKernel {
public:
explicit BlockingOp(OpKernelConstruction* ctx) : OpKernel(ctx) {}
void Compute(OpKernelContext* ctx) override {
blocking_op_state->MoveToState(0, 1);
blocking_op_state->AwaitState(2);
blocking_op_state->MoveToState(2, 3);
Tensor* out = nullptr;
const Tensor& in = ctx->input(0);
OP_REQUIRES_OK(ctx, ctx->allocate_output(0, in.shape(), &out));
out->flat<float>() = in.flat<float>();
}
};
REGISTER_KERNEL_BUILDER(Name("BlockingOp").Device(DEVICE_CPU), BlockingOp);
REGISTER_OP("BlockingOp").Input("x: float").Output("y: float").Doc("");
REGISTER_KERNEL_BUILDER(Name("BlockingOp").Device(DEVICE_SYCL), BlockingOp);
static void TestSessionInterOpThreadsImpl(bool use_function_lib) {
FunctionDefLibrary library_graph_def;
if (use_function_lib) {
const string lib = R"proto(
signature: {
name: "BlockingOpFn" input_arg: { name: "x" type: DT_FLOAT }
output_arg: { name: "y" type: DT_FLOAT }}
node_def: { name: "y" op: "BlockingOp" input: "x" }
ret: { key: "y" value: "y:y:0" } )proto";
CHECK(protobuf::TextFormat::ParseFromString(
lib, library_graph_def.add_function()));
}
FunctionLibraryDefinition flib(OpRegistry::Global(), library_graph_def);
Graph g(&flib);
Tensor t(DT_FLOAT, TensorShape({}));
t.scalar<float>()() = {1.2f};
Node* x = test::graph::Constant(&g, t);
Node* y;
if (use_function_lib) {
y = test::graph::Unary(&g, "BlockingOpFn", x);
} else {
y = test::graph::Unary(&g, "BlockingOp", x);
}
GraphDef def;
test::graph::ToGraphDef(&g, &def);
*def.mutable_library() = library_graph_def;
// Create session with two inter-op thread pools.
SessionOptions options;
// Turn off optimizations so that the blocking op doesn't get invoked during
// graph setup.
options.config.mutable_graph_options()
->mutable_optimizer_options()
->set_opt_level(OptimizerOptions_Level_L0);
(*options.config.mutable_device_count())["CPU"] = 2;
(*options.config.mutable_device_count())["GPU"] = 0;
options.config.add_session_inter_op_thread_pool();
auto* p = options.config.add_session_inter_op_thread_pool();
p->set_num_threads(1);
const int kLargePool = 0;
const int kSmallPool = 1;
std::unique_ptr<Session> session(NewSession(options));
ASSERT_TRUE(session != nullptr);
TF_ASSERT_OK(session->Create(def));
std::atomic<int32> num_done(0);
// Runs session to compute <node>:0 using inter_op thread pool <pool>.
auto add_session_run_call = [&session, &num_done](
thread::ThreadPool* tp, Node* node, int inter_op_pool) {
auto fn = [&session, inter_op_pool, node, &num_done]() {
RunOptions run_options;
run_options.set_inter_op_thread_pool(inter_op_pool);
std::vector<Tensor> outputs;
Status s = session->Run(run_options, {} /* inputs */,
{node->name() + ":0"} /* output_names */, {},
&outputs, nullptr /* run_metadata */);
TF_CHECK_OK(s);
ASSERT_EQ(1, outputs.size());
auto flat = outputs[0].flat<float>();
EXPECT_FLOAT_EQ(1.2, flat(0));
num_done.fetch_add(1);
};
tp->Schedule(fn);
};
// For blocking states:
// - Starts at 0, BlockingOp::Compute will move to 1.
// - This main thread will wait for 1, then move to 2 when other ops are done.
// Moving to 2 unblocks the blocking op, which then moves to state 3.
// Run the graph once on the non-limited pool.
thread::ThreadPool* tp1 = new thread::ThreadPool(Env::Default(), "tp1", 1);
blocking_op_state = new BlockingOpState();
add_session_run_call(tp1, y, kLargePool);
blocking_op_state->AwaitState(1);
blocking_op_state->MoveToState(1, 2);
blocking_op_state->AwaitState(3);
blocking_op_state->MoveToState(3, 0);
delete tp1;
num_done = 0;
tp1 = new thread::ThreadPool(Env::Default(), "tp1", 5);
// Launch 2 session run calls. Neither will finish until the blocking op is
// unblocked, because it is using all threads in the small pool.
add_session_run_call(tp1, y, kSmallPool);
blocking_op_state->AwaitState(1); // Wait for the blocking op to Compute.
// These will block on <BlockingOpState>.
const int kBlockedThreads = 3;
for (int i = 0; i < kBlockedThreads; ++i) {
add_session_run_call(tp1, x, kSmallPool);
}
// Launch session calls using the other inter-op pool. These will finish
// as they are in inter_op pool #2.
thread::ThreadPool* tp2 = new thread::ThreadPool(Env::Default(), "tp2", 3);
const int kUnblockedThreads = 4;
for (int i = 0; i < kUnblockedThreads; ++i) {
add_session_run_call(tp2, x, kLargePool);
}
delete tp2;
EXPECT_EQ(kUnblockedThreads, num_done.load());
// Unblock the blocked op and wait for the blocked functions to finish.
blocking_op_state->MoveToState(1, 2);
delete tp1;
EXPECT_EQ(kUnblockedThreads + kBlockedThreads + 1, num_done.load());
delete blocking_op_state;
blocking_op_state = nullptr;
}
TEST(DirectSessionTest, TestSessionInterOpThreads) {
TestSessionInterOpThreadsImpl(false /* use_function_lib */);
}
TEST(DirectSessionTest, TestSessionInterOpThreadsWithFunctions) {
TestSessionInterOpThreadsImpl(true /* use_function_lib */);
}
TEST(DirectSessionTest, TestSessionInterOpThreadsInvalidOptions) {
Graph g(OpRegistry::Global());
Tensor t(DT_FLOAT, TensorShape({}));
t.scalar<float>()() = {1.2f};
Node* x = test::graph::Constant(&g, t);
GraphDef def;
test::graph::ToGraphDef(&g, &def);
SessionOptions options;
options.config.mutable_graph_options()
->mutable_optimizer_options()
->set_opt_level(OptimizerOptions_Level_L0);
(*options.config.mutable_device_count())["CPU"] = 2;
options.config.add_session_inter_op_thread_pool();
// Wrong pool number on Run call.
std::unique_ptr<Session> session(NewSession(options));
ASSERT_TRUE(session != nullptr);
TF_ASSERT_OK(session->Create(def));
for (int pool_num = -1; pool_num <= 1; pool_num += 2) {
RunOptions run_options;
run_options.set_inter_op_thread_pool(pool_num);
std::vector<Tensor> outputs;
Status s = session->Run(run_options, {} /* inputs */,
{x->name() + ":0"} /* output_names */, {}, &outputs,
nullptr /* run_metadata */);
EXPECT_EQ(strings::StrCat(
"Invalid argument: Invalid inter_op_thread_pool: ", pool_num),
s.ToString());
}
}
TEST(DirectSessionTest, TestDirectSessionRunClose) {
// Construct a graph with a variable and a single assign.
Graph g(OpRegistry::Global());
Tensor t(DT_FLOAT, TensorShape({}));
t.scalar<float>()() = {1.2f};
Node* var_val = test::graph::Constant(&g, t);
Node* var = test::graph::Var(&g, DT_FLOAT, {});
Node* var_assign = test::graph::Assign(&g, var, var_val);
GraphDef def;
test::graph::ToGraphDef(&g, &def);
SessionOptions options;
(*options.config.mutable_device_count())["CPU"] = 2;
std::unique_ptr<Session> session(NewSession(options));
ASSERT_TRUE(session != nullptr);
TF_ASSERT_OK(session->Create(def));
// Assign a value to the var.
TF_ASSERT_OK(session->Run({} /* inputs */, {},
{var_assign->name()} /* target_nodes */, nullptr));
// Run a read on the variable to ensure that it works.
std::vector<Tensor> outputs;
TF_ASSERT_OK(session->Run(
{} /* inputs */, {var->name() + ":0"} /* output_names */, {}, &outputs));
EXPECT_EQ(t.scalar<float>()(), outputs[0].scalar<float>()());
outputs.clear();
// Close the session.
TF_ASSERT_OK(session->Close());
// Run the read on the variable to get an error.
Status s = session->Run({} /* inputs */, {},
{var_assign->name()} /* target_nodes */, nullptr);
EXPECT_EQ("Cancelled: Session has been closed.", s.ToString());
}
TEST(DirectSessionTest, TestDirectSessionPRunClose) {
GraphDef def;
Graph g(OpRegistry::Global());
Tensor first_value(DT_FLOAT, TensorShape({}));
first_value.scalar<float>()() = 1.0;
Node* first_const = test::graph::Constant(&g, first_value);
Node* first_identity = test::graph::Identity(&g, first_const);
Tensor second_value(DT_FLOAT, TensorShape({}));
second_value.scalar<float>()() = 2.0;
Node* second_const = test::graph::Constant(&g, second_value);
Node* second_identity = test::graph::Identity(&g, second_const);
Node* third = test::graph::Add(&g, first_identity, second_identity);
Node* third_identity = test::graph::Identity(&g, third);
test::graph::ToGraphDef(&g, &def);
std::unique_ptr<Session> session(CreateSession());
ASSERT_TRUE(session != nullptr);
TF_ASSERT_OK(session->Create(def));
std::vector<Tensor> outputs;
string handle;
Status s = session->PRunSetup(
{first_const->name(), second_const->name()},
{first_identity->name() + ":0", second_identity->name() + ":0",
third_identity->name() + ":0"},
{}, &handle);
TF_ASSERT_OK(s);
Tensor value_11(DT_FLOAT, TensorShape({}));
value_11.scalar<float>()() = 11.0;
Tensor value_22(DT_FLOAT, TensorShape({}));
value_22.scalar<float>()() = 22.0;
// Close the session.
TF_ASSERT_OK(session->Close());
// Feed first_const, fetch first_identity
s = session->PRun(handle, {{first_const->name(), value_11}},
{first_identity->name() + ":0"}, &outputs);
EXPECT_EQ("Cancelled: Session has been closed.", s.ToString());
}
TEST(DirectSessionTest, TestDirectSessionReset) {
// Construct a graph with a variable and a single assign.
Graph g(OpRegistry::Global());
Tensor t(DT_FLOAT, TensorShape({}));
t.scalar<float>()() = {1.2f};
Node* var_val = test::graph::Constant(&g, t);
Node* var = test::graph::Var(&g, DT_FLOAT, {});
Node* var_assign = test::graph::Assign(&g, var, var_val);
GraphDef def;
test::graph::ToGraphDef(&g, &def);
SessionOptions options;
(*options.config.mutable_device_count())["CPU"] = 2;
std::unique_ptr<Session> session(NewSession(options));
ASSERT_TRUE(session != nullptr);
TF_ASSERT_OK(session->Create(def));
// Assign a value to the var.
TF_ASSERT_OK(session->Run({} /* inputs */, {},
{var_assign->name()} /* target_nodes */, nullptr));
// Run a read on the variable to ensure that it works.
std::vector<Tensor> outputs;
TF_ASSERT_OK(session->Run(
{} /* inputs */, {var->name() + ":0"} /* output_names */, {}, &outputs));
EXPECT_EQ(t.scalar<float>()(), outputs[0].scalar<float>()());
outputs.clear();
// Reset the containers.
TF_EXPECT_OK(Reset(options, {}));
// Run the read on the variable to get an error.
// TODO(suharshs): This test only works because we close the Session in Reset.
// If we change the behavior of Reset to not close the Session, this test will
// fail, since the Variable buffer is cached by var.
Status s = session->Run({} /* inputs */, {},
{var_assign->name()} /* target_nodes */, nullptr);
EXPECT_EQ("Cancelled: Session has been closed.", s.ToString());
}
// A simple benchmark for the overhead of `DirectSession::Run()` calls
// with varying numbers of feeds/fetches.
void FeedFetchBenchmarkHelper(int num_feeds, int iters) {
testing::StopTiming();
Tensor value(DT_FLOAT, TensorShape());
value.flat<float>()(0) = 37.0;
std::vector<std::pair<string, Tensor>> inputs;
inputs.reserve(num_feeds);
std::vector<string> outputs;
Graph g(OpRegistry::Global());
for (int i = 0; i < num_feeds; ++i) {
// NOTE(mrry): We pin nodes to the "/cpu:0" device, so as not to
// measure CPU<->GPU copying overhead. We should also optimize and
// monitor this overhead where possible, but that is not the
// object of study in this benchmark.
Node* placeholder;
TF_CHECK_OK(NodeBuilder(g.NewName("Placeholder"), "PlaceholderV2")
.Attr("shape", TensorShape())
.Attr("dtype", DT_FLOAT)
.Device("/cpu:0")
.Finalize(&g, &placeholder));
Node* identity;
TF_CHECK_OK(NodeBuilder(g.NewName("Identity"), "Identity")
.Input(placeholder)
.Attr("T", DT_FLOAT)
.Device("/cpu:0")
.Finalize(&g, &identity));
inputs.push_back({placeholder->name() + ":0", value});
outputs.push_back(identity->name() + ":0");
}
GraphDef gd;
g.ToGraphDef(&gd);
SessionOptions opts;
std::unique_ptr<Session> sess(NewSession(opts));
TF_CHECK_OK(sess->Create(gd));
{
// NOTE(mrry): Ignore the first run, which will incur the graph
// partitioning/pruning overhead and skew the results.
//
// Note that we should also optimize and monitor the overhead on
// the first run, which will impact application startup times, but
// that is not the object of study in this benchmark.
std::vector<Tensor> output_values;
TF_CHECK_OK(sess->Run(inputs, outputs, {}, &output_values));
}
testing::StartTiming();
for (int i = 0; i < iters; ++i) {
std::vector<Tensor> output_values;
TF_CHECK_OK(sess->Run(inputs, outputs, {}, &output_values));
}
testing::StopTiming();
}
void BM_FeedFetch(int iters, int num_feeds) {
FeedFetchBenchmarkHelper(iters, num_feeds);
}
BENCHMARK(BM_FeedFetch)->Arg(1)->Arg(2)->Arg(5)->Arg(10);
} // namespace
} // namespace tensorflow
| [
"rohin.patel@springernature.com"
] | rohin.patel@springernature.com |
3c8774eb8dd87079414b0ad981e1e7e299c01d49 | 51e86aa676da19a0df3eaf2781032420f31771ef | /TextUI/TextUI.h | bdd854484d7a6da3454ac83298f42644c6863ff5 | [] | no_license | phamthihong/main | e1679aead14f660013e695e370ac629a24482d51 | 44a8b87468879245020fe442ac7d4f8428c96b68 | refs/heads/master | 2021-01-18T17:05:27.318138 | 2015-03-12T13:04:49 | 2015-03-12T13:04:49 | 31,930,048 | 0 | 0 | null | 2015-03-12T13:04:49 | 2015-03-10T00:27:56 | C++ | UTF-8 | C++ | false | false | 865 | h | #pragma once
#include <string>
#include "UIObject.h"
class TextUI
{
private:
static const std::string WELCOME_MSG;
static const std::string HELP_MSG;
static const std::string UNSCHEDULED_DATE_BAR;
static std::string QUALIFIER_DATE_BAR;
static std::string DEFAULT_DATE_BAR;
static struct tm convertToLocalTime(const time_t &taskDate);
static bool isUnscheduled(const time_t &taskDate);
static std::string getWkDayName(const time_t &taskDate);
static std::string getMonthName(const time_t &taskDate);
static std::string getTimeName(const time_t &taskDate);
static void printDateBar(const time_t &taskDate);
//static void printTasks(const std::vector<DS::TASK> &tasks);
public:
static void printWelcomeMsg();
static void printHelp();
static std::string getInput();
static void showOutput(UIObject uiObj);
TextUI(void);
~TextUI(void);
};
| [
"seow.yanyi@gmail.com"
] | seow.yanyi@gmail.com |
71c37fb6c4e8785dd27a69de9c47f98b9dab8051 | 092237674abcb399129d17aa1c25377a42e94e9d | /hacker-rank/sorting/running-time-of-quicksort.cpp | 306869e6beac4e619085fd8bcd0dd257a16dccd0 | [] | no_license | strncat/competitive-programming | aa4879b9efe422c5bdc7af973a93d05831d0f162 | 988c6e1ecb5e33609f710ea82f149547ed3b8d10 | refs/heads/master | 2021-07-25T03:17:31.442962 | 2020-05-26T04:05:49 | 2020-05-26T04:05:49 | 21,086,298 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,544 | cpp | //
// main.cpp
// quick
//
// Created by Fatima B on 12/25/15.
// Copyright ยฉ 2015 Fatima B. All rights reserved.
//
#include <iostream>
void print(int *a, int n) {
for (int i = 0; i < n; i++) {
printf("%d ", a[i]);
}
printf("\n");
}
void swap(int *a, int *b) {
int temp = *a;
*a = *b;
*b = temp;
}
int partition(int *a, int first, int last, int n, int *count) {
int pivot = last;
int index = first;
for (int i = first; i < last; i++) {
if (a[i] < a[pivot]) {
swap(&a[i], &a[index]);
index++;
(*count)++;
}
}
swap(&a[pivot], &a[index]);
(*count)++;
return index;
}
void quicksort(int *a, int first, int last, int n, int *count) {
if (first < last) {
int p = partition(a, first, last, n, count);
quicksort(a, first, p - 1, n, count);
quicksort(a, p + 1, last, n, count);
}
}
void insertion_sort(int *a, int n, int *count) {
for (int i = 1; i < n; i++) {
for (int j = i; j > 0; j--) {
if (a[j] < a[j - 1]) {
swap(&a[j - 1], &a[j]);
(*count)++;
}
}
}
}
int main(void) {
int n;
scanf("%d", &n);
int a[n], b[n], i;
for(i = 0; i < n; i++) {
scanf("%d", &a[i]);
b[i] = a[i];
}
int quick_count = 0, insertion_count = 0;
quicksort(a, 0, n - 1, n, &quick_count);
insertion_sort(b, n, &insertion_count);
printf("%d\n", insertion_count - quick_count);
return 0;
}
| [
"strncat"
] | strncat |
5823929b4de68a6d690876a3e0927c28cc631964 | 5082b479efeba0cc734563d9ac6a7c9fb25d217f | /strings/sortedchar_frequency.cpp | b0dc902c395ff49eb0d06adc26cbec96ac506eeb | [] | no_license | debanga/Data-Structures-and-Algorithms | fa299ab4da0992b09d6b08a5e15d34eba2b0b934 | 6a5195a2be12d43d677e00f2eadf3fe7294c2b03 | refs/heads/master | 2023-05-25T08:48:35.850631 | 2021-06-07T10:51:03 | 2021-06-07T10:51:03 | 293,933,263 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 415 | cpp | #include <iostream>
#include <string>
using namespace std;
void sortedchar_frequency(string s) {
int n = s.size();
int arr[26] = {0};
for (int i=0; i<n; ++i) {
arr[s[i]-97]++;
}
for (int i=0; i<26; ++i) {
if (arr[i]!=0) {
cout << char(i+97) << " " << arr[i] << endl;
}
}
}
int main() {
string s = "geeksforgeeks";
sortedchar_frequency(s);
} | [
"noreply@github.com"
] | debanga.noreply@github.com |
f87e9519f54adc9a5f07287b459373d0d7ba28d4 | 2f2650332e65e3fe20ca3bccafb34bef0eb59534 | /DLL/LMain.cpp | fb34d445c220410f3ce39c5b35396beb0b5d6d04 | [] | no_license | Satkarni/CDAC | e45718a23315a26bbc3a0848824218a867c7145c | 0610632dfd244ce77fe70c987ebca3138f4264a4 | refs/heads/master | 2021-07-21T23:13:50.120053 | 2017-10-31T14:21:43 | 2017-10-31T14:21:43 | 103,081,457 | 4 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 2,099 | cpp | #include"LinkedList.cpp"
#include<iostream>
#include<cstdlib>
using namespace std;
int main()
{
int choice;
LinkedList<int> objList;
do
{
system("clear");
cout<<"\n *********MENU************";
cout<<"\n 1. Add at beginning";
cout<<"\n 2. Add at end";
cout<<"\n 3. Delete from beginning";
cout<<"\n 4. Delete from end";
cout<<"\n 5. Insert at position";
cout<<"\n 6. Reverse List";
cout<<"\n 7. Check for empty";
cout<<"\n 8. Get size";
cout<<"\n 9. Display";
cout<<"\n 10. Exit";
cout<<"\n Enter your choice:";
cin>>choice;
cin.get();
switch(choice)
{
case 1: {
int ele;
cout<<"\n Enter element:";
cin>>ele;
if(!objList.addAtBegin(ele)){
cout<<"\n Insertion Failed";
cin.get();
}
else{
cout<<"\nInsertion succeded";
cin.get();
}
}break;
case 2: {
int ele;
cout<<"\n Enter element:";
cin>>ele;
if(!objList.addAtEnd(ele)){
cout<<"\n Insertion Failed";
cin.get();
}
else{
cout<<"\nInsertion succeded";
cin.get();
}
}break;
case 3: {
int no = objList.deleteFromBegin();
cout<<"\nDeleted Element:"<<no;;
cin.get();
}break;
case 4: {
int no = objList.deleteFromEnd();
cout<<"\nDeleted Element:"<<no;
cin.get();
}break;
case 5: {
int pos;
cout<<"\n Enter position";
cin>>pos;
int ele;
cout<<"\n Enter element:";
cin>>ele;
if(!objList.insertAt(pos,ele)){
cout<<"\nInsertion failed, may be insufficient size";
cin.get();
}
else{
cout<<"\nInsertion succeded";
cin.get();
}
}break;
case 6: {
if(!objList.reverse()){
cout<<"\nReverse opeartion failed";
cin.get();
}
else{
cout<<"\n List reversed";
cin.get();
}
}break;
case 7: {
if(objList.empty()){
cout<<"\n List is empty";
cin.get();
}
else{
cout<<"\n List is not empty";
cin.get();
}
}break;
case 8: {
cout<<"\n Size ="<<objList.size();
cin.get();
}break;
case 9: {
objList.display();
objList.rdisplay();
cin.get();
}break;
case 10:{}break;
}
}while(10 != choice);
return 0;
}
| [
"blahblah@rediff.com"
] | blahblah@rediff.com |
64bc312a858c7ff5f9f1338b83a1250e36298759 | 792e697ba0f9c11ef10b7de81edb1161a5580cfb | /tools/clang/include/clang/Basic/BuiltinsAArch64.def | 0869b87e32fb9281b0990977da24dfe27a74afc6 | [
"Apache-2.0",
"LLVM-exception",
"NCSA"
] | permissive | opencor/llvmclang | 9eb76cb6529b6a3aab2e6cd266ef9751b644f753 | 63b45a7928f2a8ff823db51648102ea4822b74a6 | refs/heads/master | 2023-08-26T04:52:56.472505 | 2022-11-02T04:35:46 | 2022-11-03T03:55:06 | 115,094,625 | 0 | 1 | Apache-2.0 | 2021-08-12T22:29:21 | 2017-12-22T08:29:14 | LLVM | UTF-8 | C++ | false | false | 16,124 | def | //==- BuiltinsAArch64.def - AArch64 Builtin function database ----*- C++ -*-==//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
//
// This file defines the AArch64-specific builtin function database. Users of
// this file must define the BUILTIN macro to make use of this information.
//
//===----------------------------------------------------------------------===//
// The format of this database matches clang/Basic/Builtins.def.
#if defined(BUILTIN) && !defined(LANGBUILTIN)
# define LANGBUILTIN(ID, TYPE, ATTRS, BUILTIN_LANG) BUILTIN(ID, TYPE, ATTRS)
#endif
#if defined(BUILTIN) && !defined(TARGET_HEADER_BUILTIN)
# define TARGET_HEADER_BUILTIN(ID, TYPE, ATTRS, HEADER, LANG, FEATURE) BUILTIN(ID, TYPE, ATTRS)
#endif
// In libgcc
BUILTIN(__clear_cache, "vv*v*", "i")
BUILTIN(__builtin_arm_ldrex, "v.", "t")
BUILTIN(__builtin_arm_ldaex, "v.", "t")
BUILTIN(__builtin_arm_strex, "i.", "t")
BUILTIN(__builtin_arm_stlex, "i.", "t")
BUILTIN(__builtin_arm_clrex, "v", "")
// Bit manipulation
BUILTIN(__builtin_arm_rbit, "UiUi", "nc")
BUILTIN(__builtin_arm_rbit64, "WUiWUi", "nc")
BUILTIN(__builtin_arm_cls, "UiZUi", "nc")
BUILTIN(__builtin_arm_cls64, "UiWUi", "nc")
// HINT
BUILTIN(__builtin_arm_nop, "v", "")
BUILTIN(__builtin_arm_yield, "v", "")
BUILTIN(__builtin_arm_wfe, "v", "")
BUILTIN(__builtin_arm_wfi, "v", "")
BUILTIN(__builtin_arm_sev, "v", "")
BUILTIN(__builtin_arm_sevl, "v", "")
// CRC32
BUILTIN(__builtin_arm_crc32b, "UiUiUc", "nc")
BUILTIN(__builtin_arm_crc32cb, "UiUiUc", "nc")
BUILTIN(__builtin_arm_crc32h, "UiUiUs", "nc")
BUILTIN(__builtin_arm_crc32ch, "UiUiUs", "nc")
BUILTIN(__builtin_arm_crc32w, "UiUiUi", "nc")
BUILTIN(__builtin_arm_crc32cw, "UiUiUi", "nc")
BUILTIN(__builtin_arm_crc32d, "UiUiWUi", "nc")
BUILTIN(__builtin_arm_crc32cd, "UiUiWUi", "nc")
// Memory Tagging Extensions (MTE)
BUILTIN(__builtin_arm_irg, "v*v*Ui", "t")
BUILTIN(__builtin_arm_addg, "v*v*Ui", "t")
BUILTIN(__builtin_arm_gmi, "Uiv*Ui", "t")
BUILTIN(__builtin_arm_ldg, "v*v*", "t")
BUILTIN(__builtin_arm_stg, "vv*", "t")
BUILTIN(__builtin_arm_subp, "Uiv*v*", "t")
// Memory Operations
BUILTIN(__builtin_arm_mops_memset_tag, "v*v*iz", "")
// Memory barrier
BUILTIN(__builtin_arm_dmb, "vUi", "nc")
BUILTIN(__builtin_arm_dsb, "vUi", "nc")
BUILTIN(__builtin_arm_isb, "vUi", "nc")
BUILTIN(__builtin_arm_jcvt, "Zid", "nc")
// Prefetch
BUILTIN(__builtin_arm_prefetch, "vvC*UiUiUiUi", "nc")
// System Registers
BUILTIN(__builtin_arm_rsr, "UicC*", "nc")
BUILTIN(__builtin_arm_rsr64, "WUicC*", "nc")
BUILTIN(__builtin_arm_rsrp, "v*cC*", "nc")
BUILTIN(__builtin_arm_wsr, "vcC*Ui", "nc")
BUILTIN(__builtin_arm_wsr64, "vcC*WUi", "nc")
BUILTIN(__builtin_arm_wsrp, "vcC*vC*", "nc")
// MSVC
LANGBUILTIN(__dmb, "vUi", "nc", ALL_MS_LANGUAGES)
LANGBUILTIN(__dsb, "vUi", "nc", ALL_MS_LANGUAGES)
LANGBUILTIN(__isb, "vUi", "nc", ALL_MS_LANGUAGES)
LANGBUILTIN(__yield, "v", "", ALL_MS_LANGUAGES)
LANGBUILTIN(__wfe, "v", "", ALL_MS_LANGUAGES)
LANGBUILTIN(__wfi, "v", "", ALL_MS_LANGUAGES)
LANGBUILTIN(__sev, "v", "", ALL_MS_LANGUAGES)
LANGBUILTIN(__sevl, "v", "", ALL_MS_LANGUAGES)
// Misc
BUILTIN(__builtin_sponentry, "v*", "c")
// Transactional Memory Extension
BUILTIN(__builtin_arm_tstart, "WUi", "nj")
BUILTIN(__builtin_arm_tcommit, "v", "n")
BUILTIN(__builtin_arm_tcancel, "vWUIi", "n")
BUILTIN(__builtin_arm_ttest, "WUi", "nc")
// Armv8.5-A FP rounding intrinsics
BUILTIN(__builtin_arm_frint32zf, "ff", "")
BUILTIN(__builtin_arm_frint32z, "dd", "")
BUILTIN(__builtin_arm_frint64zf, "ff", "")
BUILTIN(__builtin_arm_frint64z, "dd", "")
BUILTIN(__builtin_arm_frint32xf, "ff", "")
BUILTIN(__builtin_arm_frint32x, "dd", "")
BUILTIN(__builtin_arm_frint64xf, "ff", "")
BUILTIN(__builtin_arm_frint64x, "dd", "")
// Armv8.5-A Random number generation intrinsics
BUILTIN(__builtin_arm_rndr, "iWUi*", "n")
BUILTIN(__builtin_arm_rndrrs, "iWUi*", "n")
// Armv8.7-A load/store 64-byte intrinsics
BUILTIN(__builtin_arm_ld64b, "vvC*WUi*", "n")
BUILTIN(__builtin_arm_st64b, "vv*WUiC*", "n")
BUILTIN(__builtin_arm_st64bv, "WUiv*WUiC*", "n")
BUILTIN(__builtin_arm_st64bv0, "WUiv*WUiC*", "n")
TARGET_HEADER_BUILTIN(_BitScanForward, "UcUNi*UNi", "nh", "intrin.h", ALL_MS_LANGUAGES, "")
TARGET_HEADER_BUILTIN(_BitScanReverse, "UcUNi*UNi", "nh", "intrin.h", ALL_MS_LANGUAGES, "")
TARGET_HEADER_BUILTIN(_BitScanForward64, "UcUNi*ULLi", "nh", "intrin.h", ALL_MS_LANGUAGES, "")
TARGET_HEADER_BUILTIN(_BitScanReverse64, "UcUNi*ULLi", "nh", "intrin.h", ALL_MS_LANGUAGES, "")
TARGET_HEADER_BUILTIN(_InterlockedAdd, "NiNiD*Ni", "nh", "intrin.h", ALL_MS_LANGUAGES, "")
TARGET_HEADER_BUILTIN(_InterlockedAnd64, "LLiLLiD*LLi", "nh", "intrin.h", ALL_MS_LANGUAGES, "")
TARGET_HEADER_BUILTIN(_InterlockedDecrement64, "LLiLLiD*", "nh", "intrin.h", ALL_MS_LANGUAGES, "")
TARGET_HEADER_BUILTIN(_InterlockedExchange64, "LLiLLiD*LLi", "nh", "intrin.h", ALL_MS_LANGUAGES, "")
TARGET_HEADER_BUILTIN(_InterlockedExchangeAdd64, "LLiLLiD*LLi", "nh", "intrin.h", ALL_MS_LANGUAGES, "")
TARGET_HEADER_BUILTIN(_InterlockedExchangeSub64, "LLiLLiD*LLi", "nh", "intrin.h", ALL_MS_LANGUAGES, "")
TARGET_HEADER_BUILTIN(_InterlockedIncrement64, "LLiLLiD*", "nh", "intrin.h", ALL_MS_LANGUAGES, "")
TARGET_HEADER_BUILTIN(_InterlockedOr64, "LLiLLiD*LLi", "nh", "intrin.h", ALL_MS_LANGUAGES, "")
TARGET_HEADER_BUILTIN(_InterlockedXor64, "LLiLLiD*LLi", "nh", "intrin.h", ALL_MS_LANGUAGES, "")
TARGET_HEADER_BUILTIN(_InterlockedExchangeAdd_acq, "NiNiD*Ni", "nh", "intrin.h", ALL_MS_LANGUAGES, "")
TARGET_HEADER_BUILTIN(_InterlockedExchangeAdd_rel, "NiNiD*Ni", "nh", "intrin.h", ALL_MS_LANGUAGES, "")
TARGET_HEADER_BUILTIN(_InterlockedExchangeAdd_nf, "NiNiD*Ni", "nh", "intrin.h", ALL_MS_LANGUAGES, "")
TARGET_HEADER_BUILTIN(_InterlockedExchangeAdd8_acq, "ccD*c", "nh", "intrin.h", ALL_MS_LANGUAGES, "")
TARGET_HEADER_BUILTIN(_InterlockedExchangeAdd8_rel, "ccD*c", "nh", "intrin.h", ALL_MS_LANGUAGES, "")
TARGET_HEADER_BUILTIN(_InterlockedExchangeAdd8_nf, "ccD*c", "nh", "intrin.h", ALL_MS_LANGUAGES, "")
TARGET_HEADER_BUILTIN(_InterlockedExchangeAdd16_acq, "ssD*s", "nh", "intrin.h", ALL_MS_LANGUAGES, "")
TARGET_HEADER_BUILTIN(_InterlockedExchangeAdd16_rel, "ssD*s", "nh", "intrin.h", ALL_MS_LANGUAGES, "")
TARGET_HEADER_BUILTIN(_InterlockedExchangeAdd16_nf, "ssD*s", "nh", "intrin.h", ALL_MS_LANGUAGES, "")
TARGET_HEADER_BUILTIN(_InterlockedExchangeAdd64_acq, "LLiLLiD*LLi", "nh", "intrin.h", ALL_MS_LANGUAGES, "")
TARGET_HEADER_BUILTIN(_InterlockedExchangeAdd64_rel, "LLiLLiD*LLi", "nh", "intrin.h", ALL_MS_LANGUAGES, "")
TARGET_HEADER_BUILTIN(_InterlockedExchangeAdd64_nf, "LLiLLiD*LLi", "nh", "intrin.h", ALL_MS_LANGUAGES, "")
TARGET_HEADER_BUILTIN(_InterlockedExchange8_acq, "ccD*c", "nh", "intrin.h", ALL_MS_LANGUAGES, "")
TARGET_HEADER_BUILTIN(_InterlockedExchange8_nf, "ccD*c", "nh", "intrin.h", ALL_MS_LANGUAGES, "")
TARGET_HEADER_BUILTIN(_InterlockedExchange8_rel, "ccD*c", "nh", "intrin.h", ALL_MS_LANGUAGES, "")
TARGET_HEADER_BUILTIN(_InterlockedExchange16_acq, "ssD*s", "nh", "intrin.h", ALL_MS_LANGUAGES, "")
TARGET_HEADER_BUILTIN(_InterlockedExchange16_nf, "ssD*s", "nh", "intrin.h", ALL_MS_LANGUAGES, "")
TARGET_HEADER_BUILTIN(_InterlockedExchange16_rel, "ssD*s", "nh", "intrin.h", ALL_MS_LANGUAGES, "")
TARGET_HEADER_BUILTIN(_InterlockedExchange_acq, "NiNiD*Ni", "nh", "intrin.h", ALL_MS_LANGUAGES, "")
TARGET_HEADER_BUILTIN(_InterlockedExchange_nf, "NiNiD*Ni", "nh", "intrin.h", ALL_MS_LANGUAGES, "")
TARGET_HEADER_BUILTIN(_InterlockedExchange_rel, "NiNiD*Ni", "nh", "intrin.h", ALL_MS_LANGUAGES, "")
TARGET_HEADER_BUILTIN(_InterlockedExchange64_acq, "LLiLLiD*LLi", "nh", "intrin.h", ALL_MS_LANGUAGES, "")
TARGET_HEADER_BUILTIN(_InterlockedExchange64_nf, "LLiLLiD*LLi", "nh", "intrin.h", ALL_MS_LANGUAGES, "")
TARGET_HEADER_BUILTIN(_InterlockedExchange64_rel, "LLiLLiD*LLi", "nh", "intrin.h", ALL_MS_LANGUAGES, "")
TARGET_HEADER_BUILTIN(_InterlockedCompareExchange8_acq, "ccD*cc", "nh", "intrin.h", ALL_MS_LANGUAGES, "")
TARGET_HEADER_BUILTIN(_InterlockedCompareExchange8_nf, "ccD*cc", "nh", "intrin.h", ALL_MS_LANGUAGES, "")
TARGET_HEADER_BUILTIN(_InterlockedCompareExchange8_rel, "ccD*cc", "nh", "intrin.h", ALL_MS_LANGUAGES, "")
TARGET_HEADER_BUILTIN(_InterlockedCompareExchange16_acq, "ssD*ss", "nh", "intrin.h", ALL_MS_LANGUAGES, "")
TARGET_HEADER_BUILTIN(_InterlockedCompareExchange16_nf, "ssD*ss", "nh", "intrin.h", ALL_MS_LANGUAGES, "")
TARGET_HEADER_BUILTIN(_InterlockedCompareExchange16_rel, "ssD*ss", "nh", "intrin.h", ALL_MS_LANGUAGES, "")
TARGET_HEADER_BUILTIN(_InterlockedCompareExchange_acq, "NiNiD*NiNi", "nh", "intrin.h", ALL_MS_LANGUAGES, "")
TARGET_HEADER_BUILTIN(_InterlockedCompareExchange_nf, "NiNiD*NiNi", "nh", "intrin.h", ALL_MS_LANGUAGES, "")
TARGET_HEADER_BUILTIN(_InterlockedCompareExchange_rel, "NiNiD*NiNi", "nh", "intrin.h", ALL_MS_LANGUAGES, "")
TARGET_HEADER_BUILTIN(_InterlockedCompareExchange64_acq, "LLiLLiD*LLiLLi", "nh", "intrin.h", ALL_MS_LANGUAGES, "")
TARGET_HEADER_BUILTIN(_InterlockedCompareExchange64_nf, "LLiLLiD*LLiLLi", "nh", "intrin.h", ALL_MS_LANGUAGES, "")
TARGET_HEADER_BUILTIN(_InterlockedCompareExchange64_rel, "LLiLLiD*LLiLLi", "nh", "intrin.h", ALL_MS_LANGUAGES, "")
TARGET_HEADER_BUILTIN(_InterlockedCompareExchange128, "UcLLiD*LLiLLiLLi*", "nh", "intrin.h", ALL_MS_LANGUAGES, "")
TARGET_HEADER_BUILTIN(_InterlockedCompareExchange128_acq,"UcLLiD*LLiLLiLLi*", "nh", "intrin.h", ALL_MS_LANGUAGES, "")
TARGET_HEADER_BUILTIN(_InterlockedCompareExchange128_nf ,"UcLLiD*LLiLLiLLi*", "nh", "intrin.h", ALL_MS_LANGUAGES, "")
TARGET_HEADER_BUILTIN(_InterlockedCompareExchange128_rel,"UcLLiD*LLiLLiLLi*", "nh", "intrin.h", ALL_MS_LANGUAGES, "")
TARGET_HEADER_BUILTIN(_InterlockedOr8_acq, "ccD*c", "nh", "intrin.h", ALL_MS_LANGUAGES, "")
TARGET_HEADER_BUILTIN(_InterlockedOr8_nf, "ccD*c", "nh", "intrin.h", ALL_MS_LANGUAGES, "")
TARGET_HEADER_BUILTIN(_InterlockedOr8_rel, "ccD*c", "nh", "intrin.h", ALL_MS_LANGUAGES, "")
TARGET_HEADER_BUILTIN(_InterlockedOr16_acq, "ssD*s", "nh", "intrin.h", ALL_MS_LANGUAGES, "")
TARGET_HEADER_BUILTIN(_InterlockedOr16_nf, "ssD*s", "nh", "intrin.h", ALL_MS_LANGUAGES, "")
TARGET_HEADER_BUILTIN(_InterlockedOr16_rel, "ssD*s", "nh", "intrin.h", ALL_MS_LANGUAGES, "")
TARGET_HEADER_BUILTIN(_InterlockedOr_acq, "NiNiD*Ni", "nh", "intrin.h", ALL_MS_LANGUAGES, "")
TARGET_HEADER_BUILTIN(_InterlockedOr_nf, "NiNiD*Ni", "nh", "intrin.h", ALL_MS_LANGUAGES, "")
TARGET_HEADER_BUILTIN(_InterlockedOr_rel, "NiNiD*Ni", "nh", "intrin.h", ALL_MS_LANGUAGES, "")
TARGET_HEADER_BUILTIN(_InterlockedOr64_acq, "LLiLLiD*LLi", "nh", "intrin.h", ALL_MS_LANGUAGES, "")
TARGET_HEADER_BUILTIN(_InterlockedOr64_nf, "LLiLLiD*LLi", "nh", "intrin.h", ALL_MS_LANGUAGES, "")
TARGET_HEADER_BUILTIN(_InterlockedOr64_rel, "LLiLLiD*LLi", "nh", "intrin.h", ALL_MS_LANGUAGES, "")
TARGET_HEADER_BUILTIN(_InterlockedXor8_acq, "ccD*c", "nh", "intrin.h", ALL_MS_LANGUAGES, "")
TARGET_HEADER_BUILTIN(_InterlockedXor8_nf, "ccD*c", "nh", "intrin.h", ALL_MS_LANGUAGES, "")
TARGET_HEADER_BUILTIN(_InterlockedXor8_rel, "ccD*c", "nh", "intrin.h", ALL_MS_LANGUAGES, "")
TARGET_HEADER_BUILTIN(_InterlockedXor16_acq, "ssD*s", "nh", "intrin.h", ALL_MS_LANGUAGES, "")
TARGET_HEADER_BUILTIN(_InterlockedXor16_nf, "ssD*s", "nh", "intrin.h", ALL_MS_LANGUAGES, "")
TARGET_HEADER_BUILTIN(_InterlockedXor16_rel, "ssD*s", "nh", "intrin.h", ALL_MS_LANGUAGES, "")
TARGET_HEADER_BUILTIN(_InterlockedXor_acq, "NiNiD*Ni", "nh", "intrin.h", ALL_MS_LANGUAGES, "")
TARGET_HEADER_BUILTIN(_InterlockedXor_nf, "NiNiD*Ni", "nh", "intrin.h", ALL_MS_LANGUAGES, "")
TARGET_HEADER_BUILTIN(_InterlockedXor_rel, "NiNiD*Ni", "nh", "intrin.h", ALL_MS_LANGUAGES, "")
TARGET_HEADER_BUILTIN(_InterlockedXor64_acq, "LLiLLiD*LLi", "nh", "intrin.h", ALL_MS_LANGUAGES, "")
TARGET_HEADER_BUILTIN(_InterlockedXor64_nf, "LLiLLiD*LLi", "nh", "intrin.h", ALL_MS_LANGUAGES, "")
TARGET_HEADER_BUILTIN(_InterlockedXor64_rel, "LLiLLiD*LLi", "nh", "intrin.h", ALL_MS_LANGUAGES, "")
TARGET_HEADER_BUILTIN(_InterlockedAnd8_acq, "ccD*c", "nh", "intrin.h", ALL_MS_LANGUAGES, "")
TARGET_HEADER_BUILTIN(_InterlockedAnd8_nf, "ccD*c", "nh", "intrin.h", ALL_MS_LANGUAGES, "")
TARGET_HEADER_BUILTIN(_InterlockedAnd8_rel, "ccD*c", "nh", "intrin.h", ALL_MS_LANGUAGES, "")
TARGET_HEADER_BUILTIN(_InterlockedAnd16_acq, "ssD*s", "nh", "intrin.h", ALL_MS_LANGUAGES, "")
TARGET_HEADER_BUILTIN(_InterlockedAnd16_nf, "ssD*s", "nh", "intrin.h", ALL_MS_LANGUAGES, "")
TARGET_HEADER_BUILTIN(_InterlockedAnd16_rel, "ssD*s", "nh", "intrin.h", ALL_MS_LANGUAGES, "")
TARGET_HEADER_BUILTIN(_InterlockedAnd_acq, "NiNiD*Ni", "nh", "intrin.h", ALL_MS_LANGUAGES, "")
TARGET_HEADER_BUILTIN(_InterlockedAnd_nf, "NiNiD*Ni", "nh", "intrin.h", ALL_MS_LANGUAGES, "")
TARGET_HEADER_BUILTIN(_InterlockedAnd_rel, "NiNiD*Ni", "nh", "intrin.h", ALL_MS_LANGUAGES, "")
TARGET_HEADER_BUILTIN(_InterlockedAnd64_acq, "LLiLLiD*LLi", "nh", "intrin.h", ALL_MS_LANGUAGES, "")
TARGET_HEADER_BUILTIN(_InterlockedAnd64_nf, "LLiLLiD*LLi", "nh", "intrin.h", ALL_MS_LANGUAGES, "")
TARGET_HEADER_BUILTIN(_InterlockedAnd64_rel, "LLiLLiD*LLi", "nh", "intrin.h", ALL_MS_LANGUAGES, "")
TARGET_HEADER_BUILTIN(_InterlockedIncrement16_acq, "ssD*", "nh", "intrin.h", ALL_MS_LANGUAGES, "")
TARGET_HEADER_BUILTIN(_InterlockedIncrement16_nf, "ssD*", "nh", "intrin.h", ALL_MS_LANGUAGES, "")
TARGET_HEADER_BUILTIN(_InterlockedIncrement16_rel, "ssD*", "nh", "intrin.h", ALL_MS_LANGUAGES, "")
TARGET_HEADER_BUILTIN(_InterlockedIncrement_acq, "NiNiD*", "nh", "intrin.h", ALL_MS_LANGUAGES, "")
TARGET_HEADER_BUILTIN(_InterlockedIncrement_nf, "NiNiD*", "nh", "intrin.h", ALL_MS_LANGUAGES, "")
TARGET_HEADER_BUILTIN(_InterlockedIncrement_rel, "NiNiD*", "nh", "intrin.h", ALL_MS_LANGUAGES, "")
TARGET_HEADER_BUILTIN(_InterlockedIncrement64_acq, "LLiLLiD*", "nh", "intrin.h", ALL_MS_LANGUAGES, "")
TARGET_HEADER_BUILTIN(_InterlockedIncrement64_nf, "LLiLLiD*", "nh", "intrin.h", ALL_MS_LANGUAGES, "")
TARGET_HEADER_BUILTIN(_InterlockedIncrement64_rel, "LLiLLiD*", "nh", "intrin.h", ALL_MS_LANGUAGES, "")
TARGET_HEADER_BUILTIN(_InterlockedDecrement16_acq, "ssD*", "nh", "intrin.h", ALL_MS_LANGUAGES, "")
TARGET_HEADER_BUILTIN(_InterlockedDecrement16_nf, "ssD*", "nh", "intrin.h", ALL_MS_LANGUAGES, "")
TARGET_HEADER_BUILTIN(_InterlockedDecrement16_rel, "ssD*", "nh", "intrin.h", ALL_MS_LANGUAGES, "")
TARGET_HEADER_BUILTIN(_InterlockedDecrement_acq, "NiNiD*", "nh", "intrin.h", ALL_MS_LANGUAGES, "")
TARGET_HEADER_BUILTIN(_InterlockedDecrement_nf, "NiNiD*", "nh", "intrin.h", ALL_MS_LANGUAGES, "")
TARGET_HEADER_BUILTIN(_InterlockedDecrement_rel, "NiNiD*", "nh", "intrin.h", ALL_MS_LANGUAGES, "")
TARGET_HEADER_BUILTIN(_InterlockedDecrement64_acq, "LLiLLiD*", "nh", "intrin.h", ALL_MS_LANGUAGES, "")
TARGET_HEADER_BUILTIN(_InterlockedDecrement64_nf, "LLiLLiD*", "nh", "intrin.h", ALL_MS_LANGUAGES, "")
TARGET_HEADER_BUILTIN(_InterlockedDecrement64_rel, "LLiLLiD*", "nh", "intrin.h", ALL_MS_LANGUAGES, "")
TARGET_HEADER_BUILTIN(_ReadWriteBarrier, "v", "nh", "intrin.h", ALL_MS_LANGUAGES, "")
TARGET_HEADER_BUILTIN(__getReg, "ULLii", "nh", "intrin.h", ALL_MS_LANGUAGES, "")
TARGET_HEADER_BUILTIN(_ReadStatusReg, "LLii", "nh", "intrin.h", ALL_MS_LANGUAGES, "")
TARGET_HEADER_BUILTIN(_WriteStatusReg, "viLLi", "nh", "intrin.h", ALL_MS_LANGUAGES, "")
TARGET_HEADER_BUILTIN(_AddressOfReturnAddress, "v*", "nh", "intrin.h", ALL_MS_LANGUAGES, "")
TARGET_HEADER_BUILTIN(__mulh, "SLLiSLLiSLLi", "nh", "intrin.h", ALL_MS_LANGUAGES, "")
TARGET_HEADER_BUILTIN(__umulh, "ULLiULLiULLi", "nh", "intrin.h", ALL_MS_LANGUAGES, "")
#undef BUILTIN
#undef LANGBUILTIN
#undef TARGET_HEADER_BUILTIN
| [
"agarny@hellix.com"
] | agarny@hellix.com |
5ee0730a0d618007a080e3913949cad9edabb864 | 00dba6a26b5f18ed26fc8277f51bcb12d44c79df | /cpp/system_modules/concrete_modules/linux/exceptions/socket_close_exception.h | 945b3317d48b3f163b30ddba33eb9dee78258d3d | [] | no_license | trevorassaf/network | 15bb1d4d3e2d7a38fb80e0282a2136d1f31c21f4 | ae6ebf502b3d58ec3bad431337e9d2062aa0207c | refs/heads/master | 2021-01-18T15:14:30.807755 | 2015-08-07T00:36:59 | 2015-08-07T00:36:59 | 38,270,559 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 409 | h | #pragma once
#include <exceptions/network_exception.h>
#include <string>
namespace Network {
namespace Linux {
class SocketCloseException : public Network::NetworkException {
private:
static const int ERROR_CODE;
const std::string getErrorString(int error_number);
public:
static bool isError(int accept_error);
SocketCloseException();
};
};
};
| [
"trevor.assaf@gmail.com"
] | trevor.assaf@gmail.com |
93464da6d3a4d592f86163235f5f864e3833ff1e | a4ace471f3a34bfe7bd9aa57470aaa6e131012a9 | /LeetCode/101_Symmetric-Tree/101_Symmetric-Tree.cpp | 4d8ee32f410449b96f96ebbcab440ba18677fb72 | [] | no_license | luqian2017/Algorithm | 52beca787056e8418f74d383f4ea697f5f8934b7 | 17f281fb1400f165b4c5f8bdd3e0500f6c765b45 | refs/heads/master | 2023-08-17T05:37:14.886220 | 2023-08-08T06:10:28 | 2023-08-08T06:10:28 | 143,100,735 | 1 | 3 | null | 2020-10-19T07:05:21 | 2018-08-01T03:45:48 | C++ | UTF-8 | C++ | false | false | 815 | cpp | /**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
bool isSymmetric(TreeNode* root) {
if (!root) return true;
return helper(root->left, root->right);
}
private:
bool helper(TreeNode *root1, TreeNode *root2) {
if (!root1 && !root2) return true;
if (!root1 || !root2) return false;
if (helper(root1->left, root2->right) && helper(root1->right, root2->left)) return root1->val == root2->val;
return false;
}
}; | [
"luqian.ncsu@gmail.com"
] | luqian.ncsu@gmail.com |
5bedddb44fbac107fb6ecc468e95288a4abaa6c6 | 8402b846cd8f86034d16d72809a1483c603a9019 | /XSY/3282.cpp | 0fde919c42a6928a6b9553f80bf6d7706b05db70 | [] | no_license | syniox/Online_Judge_solutions | 6f0f3b5603c5e621f72cb1c8952ffbcbb94e3ea6 | c4265f23823e7f1c87141f5a7429b8e55e906ac6 | refs/heads/master | 2021-08-29T05:40:06.071468 | 2021-08-28T03:05:28 | 2021-08-28T03:05:28 | 136,417,266 | 2 | 3 | null | 2018-06-10T09:33:57 | 2018-06-07T03:31:17 | C++ | UTF-8 | C++ | false | false | 1,375 | cpp | #include <iostream>
#include <cstdio>
#include <algorithm>
#include <cstring>
typedef long long lint;
const int N=1e5+5;
int n,hx[N];
struct data{
int id,v;
bool operator < (const data &b) const {
return v==b.v?id<b.id:v<b.v;
}
};
inline int nxi(){
int x=0;
char c;
while((c=getchar())>'9'||c<'0');
while(x=x*10-48+c,(c=getchar())>='0'&&c<='9');
return x;
}
namespace T{
lint tr[N];
inline void init(){
memset(tr,0,sizeof(tr));
}
inline void mod(int x,const int v){
for(++x;x<=n+1;x+=x&-x) tr[x]+=v;
}
inline lint ask(int x){
lint ans=0;
for(++x;x;x-=x&-x) ans+=tr[x];
return ans;
}
inline lint ask(const int x,const int y){
if(x>y) return 0;
return ask(y)-ask(x-1);
}
}
inline lint solve(const int mid,const int nl,const int xl){
static int val[N];
static data dt[N];
lint ans=0;
T::init();
dt[0]=(data){0,0};
for(int i=1;i<=n;++i){
val[i]=val[i-1]+(hx[i]<=mid?1:-1);
dt[i]=(data){i,val[i]};
}
std::sort(dt,dt+n+1);
for(int i=0;i<=n;++i){
if(dt[i].id>=nl){
ans+=T::ask(std::max(dt[i].id-xl,0),dt[i].id-nl);
}
T::mod(dt[i].id,1);
}
return ans;
}
int main(){
#ifndef ONLINE_JUDGE
// freopen("b.in","r",stdin);
#endif
n=nxi();
for(int i=1;i<=n;++i){
hx[i]=nxi();
}
for(int i=nxi();i;--i){
const int l1=nxi(),r1=nxi(),l2=nxi(),r2=nxi();
printf("%lld\n",solve(r1,l2,r2)-solve(l1-1,l2,r2));
}
return 0;
}
| [
"noreply@github.com"
] | syniox.noreply@github.com |
863fc0bfc044c8e922c882a0e3fb7a91d6db40d2 | 0453ffb96e2c233fb04bb78e59ee70d1e66c22a3 | /tree/construct-binary-search-tree-from-preorder-traversal.cpp | da281fdbf4cce88999b6a15c0d40fedea6451f76 | [] | no_license | rakshith53/LeetCode-Solution | 4f8f08283610c54bf61135d16befad1c264eb054 | bba00e9314b4ad36f1831387a9f9fab802562b8b | refs/heads/main | 2023-02-15T14:13:04.870369 | 2021-01-13T08:15:38 | 2021-01-13T08:15:38 | 325,224,507 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 569 | cpp | /**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
int i = 0 ;
TreeNode* bstFromPreorder(vector<int>& preorder,int max=INT_MAX) {
if(i==preorder.size() || preorder[i] > max) return NULL;
TreeNode* root = new TreeNode(preorder[i++]);
root->left = bstFromPreorder(preorder,root->val);
root->right = bstFromPreorder(preorder,max);
return root;
}
};w
| [
"noreply@github.com"
] | rakshith53.noreply@github.com |
3137fbbd824ea24b7d29fe179ddb294350b57b93 | c9c10e24fb4e599c347e8f2d73a44941e4b31204 | /src/GSvar/SmallVariantSearchWidget.h | fe1c046c559780056d20df62c58ed509a9035630 | [
"MIT"
] | permissive | guoyuh/ngs-bits | ed890c69da887961c859ad55b0c44412bd3a0897 | 47a09337ebbcdc6cde8b469d47e8f4c232c5f1b0 | refs/heads/master | 2023-08-12T04:33:25.495986 | 2021-10-12T06:25:36 | 2021-10-12T06:25:36 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 734 | h | #ifndef SmallVariantSearchWidget_H
#define SmallVariantSearchWidget_H
#include <QWidget>
#include "ui_SmallVariantSearchWidget.h"
#include "Chromosome.h"
#include "GeneSet.h"
#include "VariantList.h"
class SmallVariantSearchWidget
: public QWidget
{
Q_OBJECT
public:
SmallVariantSearchWidget(QWidget* parent = 0);
void setGene(const QString& gene);
private slots:
void changeSearchType();
void updateVariants();
void copyToClipboard();
void variantContextMenu(QPoint pos);
private:
Ui::SmallVariantSearchWidget ui_;
void getVariantsForRegion(Chromosome chr, int start, int end, QByteArray gene, const GeneSet& gene_symbols, QList<QStringList>& output, QStringList& messages);
};
#endif // SmallVariantSearchWidget_H
| [
"marc.sturm@med.uni-tuebingen.de"
] | marc.sturm@med.uni-tuebingen.de |
8784830c46bceb0ce28d3667d7a5d26906c7ec77 | 6ed471f36e5188f77dc61cca24daa41496a6d4a0 | /SDK/Argent_AIController_BP_classes.h | b042025563d0307f0f8a6ebe33a479bdb82cc17b | [] | no_license | zH4x-SDK/zARKSotF-SDK | 77bfaf9b4b9b6a41951ee18db88f826dd720c367 | 714730f4bb79c07d065181caf360d168761223f6 | refs/heads/main | 2023-07-16T22:33:15.140456 | 2021-08-27T13:40:06 | 2021-08-27T13:40:06 | 400,521,086 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 774 | h | #pragma once
// Name: ARKSotF, Version: 178.8.0
#ifdef _MSC_VER
#pragma pack(push, 0x8)
#endif
namespace SDK
{
//---------------------------------------------------------------------------
// Classes
//---------------------------------------------------------------------------
// BlueprintGeneratedClass Argent_AIController_BP.Argent_AIController_BP_C
// 0x0000 (0x0871 - 0x0871)
class AArgent_AIController_BP_C : public ADino_AIController_BP_C
{
public:
static UClass* StaticClass()
{
static auto ptr = UObject::FindClass("BlueprintGeneratedClass Argent_AIController_BP.Argent_AIController_BP_C");
return ptr;
}
void UserConstructionScript();
void ExecuteUbergraph_Argent_AIController_BP(int EntryPoint);
};
}
#ifdef _MSC_VER
#pragma pack(pop)
#endif
| [
"zp2kshield@gmail.com"
] | zp2kshield@gmail.com |
8b908f2fc593a50b6fa5e60f8d69bf7208450e3c | c3a440f6e9fae7c7ccc78361e4de5cefd4e621e5 | /data structures 2017/201712shixi/test2/mapsrc/Map.h | 4dca58c2b22cbfbb57d253988e70696fc94c5e9c | [] | no_license | rex0yt/MyCods | 29a48e0b42b08645a96f8e9f2ea47db3ed96a783 | cf29fc1678b38a150c73ee9a2c5cd91ea3f08afe | refs/heads/master | 2021-01-23T04:33:58.000147 | 2018-01-05T07:01:59 | 2018-01-05T07:01:59 | 86,209,450 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,536 | h | #ifndef MAP_H_INCLUDED
#define MAP_H_INCLUDED
using namespace std;
#include <vector>
#include <iostream>
#include "mapsrc/Person.h"
#include "mapsrc/Relation.h"
#include "mapsrc/IO.h"
#define MAXVERTICES (10000)
//้ปๆฅ้พ่กจ็่พน็ฑปๅ
template <class T>
struct Edge
{
int dest;
int cost;
Edge<T> *link;
Edge() {}
Edge(int num, int weight):dest(num), cost(weight), link(NULL) {}
bool operator!=(Edge<T>& R) const;//ๅคๆญไธคๆก่พนไธ็ธ็ญ
};
//้ปๆฅ้พ่กจ็้กถ็น็ฑปๅ
template <class T>
struct Vertex
{
T data;
Edge<T> *adj;
Vertex():adj(NULL) {}
Vertex(T t):data(t),adj(NULL) {}
};
//ๅฎไน้ปๆฅ้พ่กจ
template <class V>
class Map
{
public:
Vertex<V> *NodeTable;//้กถ็น้พ่กจ
int numVertices;//ๅฝๅ้กถ็นๆฐ้
int numEdges;//่พน็ๆฐ้
int maxVertices;//ๆๅค้กถ็นๆฐ้
public:
int getVertexPos(const V vertex);//ๅๆไธช้กถ็น็็ผๅท -1่กจ็คบไธๅญๅจ
Map();//้ป่ฎคๆ้ ๅฝๆฐ
Map(vector<V> &vArray, vector<Relation> &eArray);//ๆ นๆฎ้กถ็นๅ่พน็ๆๅพ
~Map();//ๆๆๅฝๆฐ๏ผๅ ้คไธไธช้พๆฅ่กจ
V getValue(int i);//ๆ นๆฎ้กถ็น็็ผๅท่ฟๅ้กถ็นไฟกๆฏ
int getWeight(int v1,int v2);//ๅฝๆฐ่ฟๅ่พน(v1,v2)ไธ็ๆๅผ๏ผ่ฅ่ฏฅ่พนไธๅจๅพไธญ๏ผๅๅฝๆฐ่ฟๅๆๅผ0
bool setWeight(int v1,int v2, int weight);//ไฟฎๆนๅๆฅ่พน็ๆๅผ ไธๅญๅจ่ฟๅfalse
vector<Relation> getAllRelation(int v1);//่ฟๅๆๆ็ธ้ป่พน็
bool insertVertex(const V&vertex);//ๅจๅพ็้กถ็น่กจไธญๆๅ
ฅไธไธชๆฐ้กถ็นvertexใ่ฅๆๅ
ฅๆๅ๏ผๅฝๆฐ่ฟๅtrue๏ผๅฆๅfalse
bool insertEdge(int v1, int v2, int cost);//ๅจๅธฆๆๅพไธญๆๅ
ฅไธๆก่พน๏ผv1๏ผv2๏ผ๏ผ่ฅๆญค่พนๅญๅจๆๅๆฐไธๅ็๏ผๅฝๆฐ่ฟๅflase๏ผๅฆๅtrue
bool insertEdge(Relation oneRela);//ๆๅ
ฅไธๆก่พน
bool removeVertex(int v);//ๅจๅพไธญๅ ้คไธไธช้กถ็นv,vๆฏ้กถ็นๅทใ่ฅๅ ้คๆๅ๏ผๅฝๆฐ่ฟๅtrue๏ผๅฆๅfalse
bool removeEdge(int v1,int v2);//ๅจๅพไธญๅ ้คไธๆก่พน๏ผv1,v2๏ผ
int getFirstNeighbor(int v);//็ปๅบ้กถ็นไฝ็ฝฎไธบv็็ฌฌไธไธช้ปๆฅ้กถ็น็ไฝ็ฝฎ๏ผๅฆๆๆพไธๅฐ๏ผๅๅฝๆฐ่ฟๅ-1
int getNextNeighbor(int v,int w);//็ปๅบ้กถ็นv็้ปๆฅ้กถ็นw็ไธไธไธช้ปๆฅ้กถ็น็ไฝ็ฝฎ๏ผ่ฅๆฒกๆไธไธไธช้ปๆฅ้กถ็น๏ผๅๅฝๆฐ่ฟๅ-1
void Output();//ๅๅฑๅน่พๅบๅพ็ไฟกๆฏ
void Output(vector<V> &vArray, vector<Relation> &eArray);//ๅๆฐ็ป่พๅบๅพ็ไฟกๆฏ ไฟๅญ
int getNumVertices() {return numVertices;}
int getNumEdges() {return numEdges;}
};
template <class T>
bool Edge<T>::operator!=(Edge<T>& R) const
{
return (dest != R.dest)?true:false;
}
template <class V>
int Map<V>::getVertexPos(const V vertex){
for(int i=0; i<numVertices; i++)
if(NodeTable[i].data == vertex) return i;
return -1;
}
template <class V>
Map<V>::Map()
{
maxVertices = MAXVERTICES; numVertices = 0; numEdges = 0;
NodeTable = new Vertex<V>[maxVertices];//ๅๅปบ้กถ็นๆฐ็ป
if (NodeTable == NULL) {cerr << "ๅญๅจๅ้
ๅบ้๏ผ" << endl; return ;}
for (int i=0; i<maxVertices; i++)NodeTable[i].adj = NULL;
};
template <class V>
Map<V>::Map(vector<V> &vArray, vector<Relation> &eArray)
{
maxVertices = MAXVERTICES; numVertices = 0; numEdges = 0;
NodeTable = new Vertex<V>[maxVertices];//ๅๅปบ้กถ็นๆฐ็ป
for(int i=0; i<(int)vArray.size(); i++) //็ๆ่กจๅคด็ป็น
{
NodeTable[i].data = vArray[i];
NodeTable[i].adj = NULL;
numVertices ++;
}
Relation tmpEdge;
for(unsigned int i=0; i<eArray.size(); i++)
{
tmpEdge = eArray[i];
this->insertEdge(tmpEdge);
}
}
template <class V>
Map<V>::~Map()
{
for(int i=0;i<numVertices;i++)
{
Edge<V> *p = NodeTable[i].adj;
while(p!=NULL)
{
NodeTable[i].adj = p->link;
delete p;
p = NodeTable[i].adj;
}
}
delete[] NodeTable;
}
template <class V>
V Map<V>::getValue(int i)
{
return (i>=0 && i<numVertices) ? NodeTable[i].data : 0;
}
template <class V>
int Map<V>::getFirstNeighbor(int v)
{
if(v != -1)
{
Edge<V> *p = NodeTable[v].adj;
if(p != NULL) return p->dest;
}
return -1;
}
template <class V>
int Map<V>::getNextNeighbor(int v, int w)
{
if(v!=-1)
{
Edge<V> *p = NodeTable[v].adj;
while (p != NULL && p->dest != w)
p = p->link;
if (p != NULL && p->link != NULL)
return p->link->dest;
}
return -1;
}
template <class V>
int Map<V>::getWeight(int v1, int v2)
{
if(v1!=-1&&v2!=-1)
{
Edge<V> *p = NodeTable[v1].adj;
while(p!=NULL&&p->dest!=v2)
p = p->link;
if(p!= NULL) return p->cost;
}
return 0;
}
template <class V>
bool Map<V>::setWeight(int v1,int v2, int weight)
{
Edge<V> *pnt = NodeTable[v1].adj;
while(pnt != NULL)
{
if(pnt->dest == v2)
{
pnt->cost = weight;
break;
}
pnt = pnt->link;
}
pnt = NodeTable[v2].adj;
while(pnt != NULL)
{
if(pnt->dest == v1)
{
pnt->cost = weight;
break;
}
pnt = pnt->link;
}
return true;
}
template<class V>
vector<Relation> Map<V>::getAllRelation(int v1)
{
vector<Relation> ans;
Edge<V> *pnt = NodeTable[v1].adj;
while(pnt != NULL)
{
int vertex = this->getValue(pnt->dest);
int weight = pnt->cost;
ans.push_back(Relation(getValue(v1),vertex,weight));
pnt = pnt->link;
}
return ans;
}
template <class V>
bool Map<V>::insertVertex(const V& vertex)
{
if(numVertices == maxVertices)
return false;
NodeTable[numVertices].data = vertex;
numVertices++;
return true;
}
template <class V>
bool Map<V>::removeVertex(int v)
{
if(numVertices==1 || v<0 || v>=numVertices)//ๅคๆญ้กถ็น็ๅๆณๆง
return false;
Edge<V> *p,*s,*tmp;
int k;
while(NodeTable[v].adj!= NULL)
{
p = NodeTable[v].adj; k = p->dest;
s = NodeTable[k].adj; tmp = NULL;
while(s!= NULL && s->dest!=v)
{
tmp = s;
s = s->link;
}
if(s!= NULL)
{
if(tmp==NULL)
NodeTable[k].adj = s->link;
else tmp->link = s->link;
delete s;
}
NodeTable[v].adj = p->link;
delete p;
numEdges--;
}
numVertices--;
NodeTable[v].data = NodeTable[numVertices].data;
p = NodeTable[v].adj = NodeTable[numVertices].adj;
while(p != NULL)
{
s =NodeTable[p->dest].adj;
while(s!=NULL)
if(s->dest == numVertices)
{
s->dest = v;
break;
}
else s = s->link;
p = p->link;
}
return true;
}
template <class V>
bool Map<V>::insertEdge(int v1,int v2, int weight)
{
if(v1>=0 && v1<numVertices && v2>=0 && v2<numVertices)
{
Edge<V> *q, *p=NodeTable[v1].adj;
while(p!=NULL&&p->dest!=v2)
p = p ->link;
if(p!=NULL) return false;
p = new Edge<V>; q = new Edge<V>;
p->dest = v2; p->cost = weight;
p -> link = NodeTable[v1].adj;
NodeTable[v1].adj = p;
q -> dest = v1; q -> cost = weight;
q -> link = NodeTable[v2].adj;
NodeTable[v2].adj=q;
numEdges ++; return true;
}
return false;
}
template <class V>
bool Map<V>::insertEdge(Relation oneRela)
{
if(this->insertEdge(this->getVertexPos(oneRela.getPer1()),
this->getVertexPos(oneRela.getPer2()),oneRela.getWeight()))
return true;
return false;
}
template <class V>
bool Map<V>::removeEdge(int v1, int v2) {
if (v1 != -1 && v2 != -1)
{
Edge<V> *p = NodeTable[v1].adj, *q = NULL, *s = p;
while (p != NULL && p->dest != v2)
{
q = p;p = p->link;
}
if (p != NULL)
{
if(p == s) NodeTable[v1].adj = p->link;
else q->link = p->link;
delete p;
}
else return false;
p = NodeTable[v2].adj;
q = NULL, s = p;
while (p->dest != v1)
{
q = p; p = p->link;
}
if (p == s) NodeTable[v2].adj = p->link;
else q->link = p->link;
delete p;
return true;
}
return false;
}
template <class V>
void Map<V>::Output()
{
Edge<V> *tmp;
int len = this->getNumVertices();
for(int i=0; i<len; i++)
{
cout << this->NodeTable[i].data << endl;
tmp = this->NodeTable[i].adj;
while(tmp != NULL)
{
cout << this->getValue(tmp->dest) << " " << tmp->cost << endl;
tmp = tmp->link;
}
}
}
template <class V>
void Map<V>::Output(vector<V> &vArray, vector<Relation> &eArray)
{
}
#endif // MAP_H_INCLUDED
| [
"yt1290401516@outlook.com"
] | yt1290401516@outlook.com |
fa5062aef9147cd58bec1d8b62b333bcf4a88385 | 82d483e0a15b3d39adbc945e7a78d3632c9b7d15 | /GraphTheory/Dijkstra/DijkstraPQ.cpp | 4716af001f3ffe640f9b638850d36fd964717e2a | [] | no_license | PandeyAditya14/APS2020 | 18dfb3f1ef48f27a0b50c1184c3749eab25e2a1a | d0f69b56de5656732aff547a88a7c79a77bcf6b1 | refs/heads/master | 2022-08-10T13:40:13.119026 | 2022-08-01T03:22:37 | 2022-08-01T03:22:37 | 236,135,975 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,534 | cpp | /**
* @file DijkstraPQ.cpp
* @author Aditya Kumar Pandey (aditya141199@gmail.com)
* @brief This is the priority queue implementation of Dijkstra algo
* @version 0.1
* @date 2020-07-07
*
* @copyright Copyright (c) 2020
*
*/
#include<bits/stdc++.h>
using namespace std;
typedef pair<int,int> ii;
const int INF = INT_MAX;
void dijkstra(vector<ii> adj[] , vector<int> &p , vector<int> &d , int source , int n){
d.assign(n,INF);
p.assign(n,-1);
d[source] = 0;
p[source] = source;
priority_queue<ii ,vector<ii>, greater<ii>> q;
vector<bool> visited(n,false);
q.push(ii(0,source));
while(!q.empty()){
int v = q.top().second;
int d_v = q.top().first;
q.pop();
if(d_v != d[v])
continue;
for(auto edge : adj[v]){
int to = edge.first;
int weight = edge.second;
if(d[to] > d[v] + weight){
d[to] = d[v] + weight;
p[to] = v;
q.push(ii(d[to] , to));
}
}
}
}
int main(){
int n , m;
cin>>n>>m;
vector<ii> *adj;
adj = new vector<ii>[n];
vector<int> p , d;
for(int i = 0 ; i<m ; i++){
int u , v , w;
cin>>u>>v>>w;
adj[u].push_back(ii(v,w));
}
dijkstra(adj,p,d,0,n);
vector <int> path;
int i;
for(i = n-1 ; i!=p[i] && i!=-1 ; i=p[i]) path.push_back(i);
path.push_back(i);
reverse(path.begin() , path.end()) ;
for(auto node : path) cout<<node<<"=>";
cout<<"/";
} | [
"aditya141199@gmail.cm"
] | aditya141199@gmail.cm |
3622f61cecfa33f7f97f9267e10acc5f1099a71e | 3edba00beb1d1f84778a73b13334622423be6dfc | /Thuรขฬฃt toaฬn ฦฐฬng duฬฃng/ADDMOD/main.cpp | c55b622644b23a6e88ec68159ca4fb0d8763c685 | [] | no_license | tranha31/TTUD | 616261fbdb6b68c05f535ff96e2d729231ba8b70 | e68bbb6f19703fe9ed889365b147e730c960d842 | refs/heads/main | 2023-03-27T06:27:24.054329 | 2021-03-29T01:43:04 | 2021-03-29T01:43:04 | 350,740,290 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 348 | cpp | #include <iostream>
#include <math.h>
#include <vector>
using namespace std;
int main()
{
unsigned long long a, b;
cin >> a;
cin >> b;
if(a%1000000007+b%1000000007 < 1000000007)
{
cout << (a%1000000007+b%1000000007);
}
else
{
cout << (a%1000000007+b%1000000007 - 1000000007);
}
return 0;
}
| [
"tranquangha31082000@gmail.com"
] | tranquangha31082000@gmail.com |
25f7668e8d08578d9a642b46ce8abd2a50202f9f | ff4a3815a179cc92668c841ed093f8c47eda334c | /cnf-sat-vc.hpp | b8e18d50b344655a4b3c4160b8926aa4d8f79e93 | [] | no_license | adkulas/Intersection-Camera-Optimizer | 96cf5b76bb4d58d9b59f7bfc114833683486c9f4 | 170bf4adc43fae369c98c1a073b274c43671a041 | refs/heads/master | 2020-04-09T01:13:39.968811 | 2018-12-10T04:17:31 | 2018-12-10T04:17:31 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,082 | hpp | #pragma once
#include <iostream>
#include <vector>
#include <minisat/core/SolverTypes.h>
#include <minisat/core/Solver.h>
std::string print_vector(std::vector<int> result_paths);
class VertexCover {
private:
int vertices;
std::vector< std::pair<int,int> > edges;
Minisat::Var toVar(int row, int column, int k);
bool check_valid_input(std::vector< std::pair<int,int> > edges);
void add_clause_at_least_one_in_cover(Minisat::Solver& solver, int k);
void add_clause_vertex_only_once(Minisat::Solver& solver, int k);
void add_clause_one_per_cover_pos(Minisat::Solver& solver, int k);
void add_clause_every_edge_covered(Minisat::Solver& solver, int k);
bool solve(Minisat::Solver& solver, int k);
std::vector<int> get_path(Minisat::Solver& solver, int k);
public:
VertexCover ( int v, std::vector< std::pair<int,int> > edges );
// Accessors
int get_vertices() const;
// Mutators
void add_edges(std::vector< std::pair<int,int> > edges);
std::string bin_search_vcover();
std::string lin_search_vcover();
}; | [
"adam.kulas1@gmail.com"
] | adam.kulas1@gmail.com |
01b2051c5bc31401462ee42c5a6296913a4e48f1 | 5a63bd6870346aa6593233b990303e743cdb8861 | /SDK/BP_QuickAccesPoint_Trapshot_classes.h | f17723ee8cd251c158100bf93897cd4aaec8d687 | [] | no_license | zH4x-SDK/zBlazingSails-SDK | dc486c4893a8aa14f760bdeff51cea11ff1838b5 | 5e6d42df14ac57fb934ec0dabbca88d495db46dd | refs/heads/main | 2023-07-10T12:34:06.824910 | 2021-08-27T13:42:23 | 2021-08-27T13:42:23 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,393 | h | #pragma once
// Name: BS, Version: 1.536.0
#ifdef _MSC_VER
#pragma pack(push, 0x8)
#endif
namespace SDK
{
//---------------------------------------------------------------------------
// Classes
//---------------------------------------------------------------------------
// BlueprintGeneratedClass BP_QuickAccesPoint_Trapshot.BP_QuickAccesPoint_Trapshot_C
// 0x0015 (0x0418 - 0x0403)
class ABP_QuickAccesPoint_Trapshot_C : public ABP_QuickAccesPointBase_C
{
public:
unsigned char UnknownData00[0x5]; // 0x0403(0x0005) MISSED OFFSET
struct FPointerToUberGraphFrame UberGraphFrame; // 0x0408(0x0008) (ZeroConstructor, Transient, DuplicateTransient)
class UStaticMeshComponent* StaticMesh; // 0x0410(0x0008) (BlueprintVisible, ZeroConstructor, InstancedReference, IsPlainOldData)
static UClass* StaticClass()
{
static auto ptr = UObject::FindClass("BlueprintGeneratedClass BP_QuickAccesPoint_Trapshot.BP_QuickAccesPoint_Trapshot_C");
return ptr;
}
void UserConstructionScript();
void ReceiveBeginPlay();
void GiveResources();
void AmountRepEvent();
void ExecuteUbergraph_BP_QuickAccesPoint_Trapshot(int EntryPoint);
};
}
#ifdef _MSC_VER
#pragma pack(pop)
#endif
| [
"zp2kshield@gmail.com"
] | zp2kshield@gmail.com |
cc258861b6004ad269053fe9fa359f1cf91c2136 | c82478b4c2be2d9c76ddb44239c2602d6e1f7aaf | /NAKGe/NaGeGeometry2D.h | e9170f0f4fe017080c1774184f45fc68a66e72c3 | [] | no_license | cybaj/NAK | 8b6d66c87b2cf7461b4868f6abcb766b42f8b248 | bff483f3466a82dbe52b3a283c5eeb55b9936944 | refs/heads/master | 2016-08-11T14:21:50.108499 | 2015-11-30T10:05:51 | 2015-11-30T10:05:51 | 45,076,165 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,158 | h |
/***************************************************************************
* NaGeGeometry2D.h
****************************************************************************/
#ifndef _GEOMETRY2D_H
#define _GEOMETRY2D_H
#ifdef NAKGE_EXPORTS
#define NAKGE_API __declspec(dllexport)
#else
#define NAKGE_API __declspec(dllimport)
#endif
enum Geometry2DType { GEPOINT2D, GEONEAXIS2D, GECURVE2D };
class NaGePoint2D;
class NaGeVector2D;
class NaGeOneAxis2D;
class NAKGE_API NaGeGeometry2D
{
public:
NaGeGeometry2D();
virtual ~NaGeGeometry2D();
virtual void Translate(const NaGeOneAxis2D&, const double& amt);
virtual void Translate(double dx, double dy) = 0;
virtual void Translate(const NaGeVector2D&) = 0;
virtual void Translate(const NaGePoint2D&, const NaGePoint2D&) = 0;
virtual void Rotate(const NaGePoint2D&, double) = 0;
virtual void Scale(const NaGePoint2D&, double) = 0;
virtual void Mirror(const NaGePoint2D&) = 0;
virtual void Mirror(const NaGeOneAxis2D&) = 0;
inline Geometry2DType GeomType() const { return geomType; }
private:
static int refCount;
protected:
Geometry2DType geomType;
};
#endif /* _GEOMETRY2D_H */
| [
"arx119@empas.com"
] | arx119@empas.com |
40d3092bf94ed08b0cf8c2662b711085b15b87b8 | 54f15d265bfbf070bc36e0bdc2c4f705093580b4 | /threadPoolDemo/threadqueue.h | 5cbe13be1ff21bcbe0109c0e2b79c68e11a29c88 | [] | no_license | zhaoyujie199196/threadPoolDemo | bc1350d371bf18283b1d56ebd22aaa0646a9bd5e | d10f9fb6096e10be6128e41e4ca2e21968a6d0c5 | refs/heads/master | 2020-04-19T10:14:21.531942 | 2019-01-29T10:23:04 | 2019-01-29T10:23:04 | 168,134,371 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,129 | h | #ifndef THREADQUEUE_H
#define THREADQUEUE_H
#include <QList>
#include <iostream>
#include <mutex>
#include <condition_variable>
template <class T>
class ThreadQueue
{
public:
ThreadQueue(int nMaxCount);
void put(const T &t);
void put(T &&t);
T take(bool &bSuccess);
void close();
protected:
template <class F>
void add(F &&t);
bool notFull();
bool notEmpty();
protected:
std::mutex m_mutex;
std::condition_variable m_NotEmptyCondition;
std::condition_variable m_NotFullConditin;
QList<T> m_queue;
int m_nMaxCount = 0;
bool m_bHasQuit = false;
};
template<class T>
ThreadQueue<T>::ThreadQueue(int nMaxCount)
: m_nMaxCount(nMaxCount)
{
}
template <class T>
void ThreadQueue<T>::put(const T &t)
{
add(t);
}
template <class T>
void ThreadQueue<T>::put(T &&t)
{
add(std::forward<T>(t));
}
template <class T>
T ThreadQueue<T>::take(bool &bSuccess)
{
std::unique_lock<std::mutex> locker(m_mutex);
m_NotEmptyCondition.wait(locker, [this]{return notEmpty() || m_bHasQuit;});
if (m_bHasQuit)
{
bSuccess = false;
return std::move(T());
}
else
{
T t = m_queue.takeFirst();
bSuccess = true;
m_NotFullConditin.notify_one();
return std::move(t);
}
}
template <class T>
template <class F>
void ThreadQueue<T>::add(F &&t)
{
std::unique_lock<std::mutex> locker(m_mutex);
m_NotFullConditin.wait(locker, [this]{return notFull() || m_bHasQuit;});
if (m_bHasQuit)
return;
m_queue.append(t);
m_NotEmptyCondition.notify_one();
}
template <class T>
bool ThreadQueue<T>::notFull()
{
return m_queue.size() < m_nMaxCount;
}
template <class T>
bool ThreadQueue<T>::notEmpty()
{
return !m_queue.isEmpty();
}
template<class T>
void ThreadQueue<T>::close()
{
std::unique_lock<std::mutex> locker(m_mutex);
m_queue.clear();
m_bHasQuit = true;
m_NotEmptyCondition.notify_all();
m_NotFullConditin.notify_all();
}
#endif // THREADQUEUE_H
| [
"1147782219@qq.com"
] | 1147782219@qq.com |
2e295a45f4fad1d3073882f2a5a760eef892e5ea | fe1b2ad7fd98fc2ccfa2b9aae75b77209a15f19c | /tmp/class_function.cpp | 26f457a199a4ff3eb1460dc5d53d0bedad05cf52 | [] | no_license | timtingwei/cppd | 58519d403272b4ea35ab350bdfbd771d0ce1ccde | 8e0caf97fbed3a0c24ab21ca44f1750f376534f8 | refs/heads/master | 2018-10-10T14:58:09.419241 | 2018-07-06T22:13:06 | 2018-07-06T22:13:06 | 109,270,504 | 1 | 2 | null | 2018-07-14T13:22:38 | 2017-11-02T13:46:59 | C++ | UTF-8 | C++ | false | false | 2,795 | cpp | /* ------------------------------
Copyright <2018> [Tim Hu]
email: timtingwei@hotamail.com
------------------------------
File:class_function.cpp
Date:Wed Jan 10 08:50:01 CST 2018
-----------------------------
*/
/*
ๅฝๆฐๅฏน่ฑก, ๅฏน่ฑกๅฎ็ฐๅฝๆฐ็ๅ่ฝ
*/
#include <iostream>
// ๅฎไนไธไธชๅฝๆฐๅฏน่ฑก
class Sum{
public:
int sum;
void operator()(int iarr[], int n) {
for (int i = 0; i < n; i++)
sum += iarr[i];
std::cout << "sum = " << sum << std::endl;
}
};
// ๅฝๆฐๅฏน่ฑกไฝไธบๅฆไธไธชๅฝๆฐ็ๅฝขๅ
template <typename CLS>
void f(CLS & c) {
int iarr[] = {3, 6, 9};
int n = 3;
c(iarr, n);
}
template <typename T>
class Vector {
private:
T* _elem; int _size; int _capacity;
public:
// ๆ้ ๅฝๆฐ
Vector<T>(T* tarr, int lo, int hi) {
copyFrom(tarr, lo, hi);
}
// ๅฝๆฐ่ฐ็จๆถๅไธๅธฆ็ฑปๅ
// ๅคๅถๅฝๆฐ
void copyFrom(T* tarr, int lo, int hi) {
_elem = new T[_capacity = 2*(hi - lo)];
_size = hi - lo;
std::cout << "*tarr = " << tarr[1] << std::endl;
std::cout << "*_elem = " << *_elem << std::endl;
for (int i = 0; i < _size; i++) {*(_elem+i) = tarr[i];}
}
// ไธบไปไนไธๅฎ่ฆไธบ_elemๅ้
็ฉบ้ด?
// ๅฏป็งฉ่ฎฟ้ฎ
void operator[](int i) const {return *(_elem+i);}
// ้ๅๆไฝ
template <typename VST> void traverse(VST visit);
// ้่ฝฝๅ็ฝฎ++
void operator++(int);
void print_vector() const {
std::cout << "-- ---------print vector------- -- " << std::endl;
std::cout << "_size = " << _size << std::endl;
for (int i = 0; i < _size; i++)
std::cout << "_elem[" << i << "] = " << _elem[i] << std::endl;
}
};
template <typename T> template <typename VST>
void Vector<T>::traverse(VST visit) {
// ๅฏนๆฏไธชๅ
็ด ๆง่กvisitๆไฝ
for (int i = 0; i < _size; i++) {visit(_elem[i]);}
}
// ไธบไปไนไธ่ฝ็จๅผ็จ็ฑปๅ?
// no known conversion for argument 1 from โIncrease<int>โ to โIncrease<int>&โ
/*
template <typename T>
void Vector<T>::operator++(int) {
for (int i = 0; i < _size; i++) {*(_elem + i)++;}
}
*/
template <typename T>
struct Increase { // Increaseๅฏน่ฑกๅณๆฏvisitๅฏนๅบ็ๆไฝ
void operator()(T& e) {e++;} // T็ฑปๅๅทฒ็ป้่ฝฝ++็ฌฆๅท, Tๅฏนๅบ็ๆฏ*_elem็็ฑปๅint
};
/*
template <typename T>
void increase(Vector<T> V) {
V.traverse(Increase(T& e));
}
*/
template <typename T>
void increase(Vector<T> V) {
V.traverse(Increase<T>());
}
// ไธบไปไนไธ็จๅฎไพๅ, ๅธฆๅ
ฅๅๆฐไพฟๅฏ็ดๆฅ่ฐ็จ??
int main() {
// ..
// f();
// Sum()
Sum s;
int iarr[] = {1, 2, 3, 4, 5, 7};
int n = 6;
s(iarr, n);
Sum s1;
f(s1);
int lo = 0, hi = 6;
Vector<int> v(iarr, lo, hi);
v.print_vector();
increase(v);
v.print_vector();
Sum(iarr, n);
return 0;
}
| [
"timtingwei@hotmail.com"
] | timtingwei@hotmail.com |
d65745fa22ecaef2151973c9e469266af9070858 | 65200834c3b1bb73accb5bdfaf90b5bcf0c992d0 | /Projet/Code/Entities/Streumons/Streumon.cpp | 5cd1460505e5726f81e673d9f8a0277872d0e36c | [] | no_license | NicolasQuero/Streumons-RPG | 3070702558f6071cd63429e8f2d6444e1e13d5fe | dc738318f39b9b94b194c9b1842615637fda72d3 | refs/heads/master | 2020-12-05T14:00:24.124108 | 2020-01-14T20:44:38 | 2020-01-14T20:44:38 | 232,132,137 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,428 | cpp | #include "Streumon.hpp"
using namespace std;
Streumon::Streumon(char monsterLetter, int x, int y, int hp, int dmg) : Entity(monsterLetter, x, y, hp, dmg) {}
bool Streumon::moveBy(Pos movement, Entity *J, vector<vector<char>> &charMap, vector<Entity*> &streumons) {
Pos targetPos = this->pos + movement;
int i=charMap.size();
int j=charMap[0].size();
if ( charMap[targetPos.x][targetPos.y] == '#' || charMap[targetPos.x][targetPos.y] == 'X') { // WALL DETECTED
return false;
}
else if (targetPos.x==0||targetPos.y==0||targetPos.x==i-1||targetPos.y==j-1)
return false;
else {
for (Entity* streumon : streumons) {
if (streumon->pos.y == targetPos.y && streumon->pos.x == targetPos.x) // OTHER MONSTER AT TARGET LOCATION
return false;
}
if (J->pos.y == targetPos.y && J->pos.x == targetPos.x) { // START COMBAT WITH PLAYER
J->addScore(this);
Combat newCombat = Combat(this, J);
cout << "COMBAT" << endl;
newCombat.startCombat();
return true;
}
}
this->pos += movement; // NO COLLISION, MOVEMENT IS DONE
return true;
}
bool Streumon::moveMonsterAtRandom(Entity *J, vector<vector<char>> &charMap, vector<Entity*> &streumons) {
int rand9 = rand()%9;
return moveBy(DEPLACEMENTS_POS[rand9], J, charMap, streumons);
}
| [
"noreply@github.com"
] | NicolasQuero.noreply@github.com |
5b90e509eae308efbc21cda343be6d405a64a742 | acc2f5336d768a7d86dbd2eec441283cfd11d52d | /src/Core/SGDeleteGuildOKHandler.cpp | 05e9a2d786b2c4d7d0a53c20fd0df016adc7ac25 | [] | no_license | stevexk/server | 86df9e8c2448ad97db9c3ab86820beec507ef092 | 4ddb6e7cfa510bb13ccd87f56db008aa1be1baad | refs/heads/master | 2020-01-23T22:00:57.359964 | 2015-09-18T14:58:27 | 2015-09-18T14:58:27 | null | 0 | 0 | null | null | null | null | UHC | C++ | false | false | 7,129 | cpp | //----------------------------------------------------------------------
//
// Filename : SGDeleteGuildOKHandler.cpp
// Written By : Reiot
// Description :
//
//----------------------------------------------------------------------
// include files
#include "SGDeleteGuildOK.h"
#ifdef __GAME_SERVER__
#include "Assert1.h"
#include "DB.h"
#include "Guild.h"
#include "GuildManager.h"
#include "PCFinder.h"
#include "Player.h"
#include "PlayerCreature.h"
#include "Properties.h"
#include "Zone.h"
#include "ResurrectLocationManager.h"
#include "GCSystemMessage.h"
#include "GCModifyInformation.h"
#include "GCModifyGuildMemberInfo.h"
#include "GCOtherModifyInfo.h"
#include "GuildUnion.h"
#endif
//----------------------------------------------------------------------
//
// SGDeleteGuildOKHandler::execute()
//
//----------------------------------------------------------------------
void SGDeleteGuildOKHandler::execute (SGDeleteGuildOK* pPacket )
throw(ProtocolException , Error )
{
__BEGIN_TRY
#ifdef __GAME_SERVER__
// ๊ธธ๋ ์์งํธ์ ์๋ ๋ฉค๋ฒ๋ฅผ warp ์ํจ๋ค.
// ๊ธธ๋ ์์งํธ๋ฅผ ์ญ์ ํ๋ค.
// ๋ฉค๋ฒ warp์ ๊ธธ๋ ์์งํธ ์ญ์ ์ ๋ค๋ฅธ ์ฐ๋ ๋์์ ZoneGroup Thread ๋ด๋ถ์์ ์ผ์ด๋๊ฒ ํด์ผ ๋ณํ์ด ์์ ๋ฏ ํ๋ค.
// ์ผ๋จ์ ๊ฑ ๋๋ค. Portal ์ด ๋งํ๋ฏ๋ก ๋ค์ ๋ค์ด๊ฐ ์ ์์ ๊ฒ์ด๋ค.
Assert(pPacket != NULL);
// ๊ธธ๋๋ฅผ ๊ฐ์ ธ์จ๋ค.
Guild* pGuild = g_pGuildManager->getGuild(pPacket->getGuildID());
try { Assert(pGuild != NULL); } catch (Throwable& ) { return; }
// ๊ธธ๋ ํ๋ ์ค์ธ ์ํ์์์ ํด์ฒด์ธ์ง ๋๊ธฐ ์ค์ธ ์ํ์์์ ํด์ฒด์ธ์ง ๊ตฌ๋ณํ๋ค.
if (pGuild->getState() == Guild::GUILD_STATE_ACTIVE )
{
HashMapGuildMember& Members = pGuild->getMembers();
HashMapGuildMemberItor itr = Members.begin();
for (; itr != Members.end(); itr++ )
{
GuildMember* pGuildMember = itr->second;
// ์ ์ํด ์์ผ๋ฉด
__ENTER_CRITICAL_SECTION((*g_pPCFinder))
Creature* pCreature = g_pPCFinder->getCreature_LOCKED(pGuildMember->getName());
if (pCreature != NULL && pCreature->isPC() )
{
Player* pPlayer = pCreature->getPlayer();
Assert(pPlayer != NULL);
PlayerCreature* pPlayerCreature = dynamic_cast<PlayerCreature*>(pCreature);
Assert(pPlayerCreature != NULL);
// Slayer, Vampire ์ ๊ธธ๋ ์์ด๋๋ฅผ ๋ฐ๊พผ๋ค.
if (pPlayerCreature->isSlayer() )
{
pPlayerCreature->setGuildID(99); // ์ฌ๋ ์ด์ด ๊ฐ์
์ํ ์ํ์ ๊ธธ๋ ID
// ํด๋ผ์ด์ธํธ์ ๊ธธ๋ ์์ด๋๊ฐ ๋ฐ๊ผ์์ ์๋ฆฐ๋ค.
GCModifyGuildMemberInfo gcModifyGuildMemberInfo;
gcModifyGuildMemberInfo.setGuildID(pPlayerCreature->getGuildID());
gcModifyGuildMemberInfo.setGuildName("");
gcModifyGuildMemberInfo.setGuildMemberRank(GuildMember::GUILDMEMBER_RANK_DENY);
pPlayer->sendPacket(&gcModifyGuildMemberInfo);
}
else if (pPlayerCreature->isVampire() )
{
pPlayerCreature->setGuildID(0); // ๋ฑํ์ด์ด ๊ฐ์
์ํ ์ํ์ ๊ธธ๋ ID
// ํด๋ผ์ด์ธํธ์ ๊ธธ๋ ์์ด๋๊ฐ ๋ฐ๊ผ์์ ์๋ฆฐ๋ค.
GCModifyGuildMemberInfo gcModifyGuildMemberInfo;
gcModifyGuildMemberInfo.setGuildID(pPlayerCreature->getGuildID());
gcModifyGuildMemberInfo.setGuildName("");
gcModifyGuildMemberInfo.setGuildMemberRank(GuildMember::GUILDMEMBER_RANK_DENY);
pPlayer->sendPacket(&gcModifyGuildMemberInfo);
}
else if (pPlayerCreature->isOusters() )
{
pPlayerCreature->setGuildID(66); // ์์ฐ์คํฐ์ฆ ๊ฐ์
์ํ ์ํ์ ๊ธธ๋ ID
// ํด๋ผ์ด์ธํธ์ ๊ธธ๋ ์์ด๋๊ฐ ๋ฐ๊ผ์์ ์๋ฆฐ๋ค.
GCModifyGuildMemberInfo gcModifyGuildMemberInfo;
gcModifyGuildMemberInfo.setGuildID(pPlayerCreature->getGuildID());
gcModifyGuildMemberInfo.setGuildName("");
gcModifyGuildMemberInfo.setGuildMemberRank(GuildMember::GUILDMEMBER_RANK_DENY);
pPlayer->sendPacket(&gcModifyGuildMemberInfo);
}
// ์ฃผ์์ ํด๋ผ์ด์ธํธ์ ๊ธธ๋ ์์ด๋๊ฐ ๋ฐ๊ผ์์ ์๋ฆฐ๋ค.
GCOtherModifyInfo gcOtherModifyInfo;
gcOtherModifyInfo.setObjectID(pCreature->getObjectID());
gcOtherModifyInfo.addShortData(MODIFY_GUILDID, pPlayerCreature->getGuildID());
Zone* pZone = pCreature->getZone();
Assert(pZone != NULL);
pZone->broadcastPacket(pCreature->getX(), pCreature->getY(), &gcOtherModifyInfo, pCreature);
}
__LEAVE_CRITICAL_SECTION((*g_pPCFinder))
// Guild Member ๊ฐ์ฒด๋ฅผ ์ญ์ ํ๋ค.
SAFE_DELETE(pGuildMember);
}
// ๊ธธ๋ ๋ฉค๋ฒ ๋งต์ ์ญ์ ํ๋ค.
Members.clear();
// ๊ธธ๋ ๋งค๋์ ์์ ๊ธธ๋๋ฅผ ์ญ์ ํ๋ค.
g_pGuildManager->deleteGuild(pGuild->getID());
// ๊ธธ๋ ๊ฐ์ฒด๋ฅผ ์ญ์ ํ๋ค.
SAFE_DELETE(pGuild);
}
else if (pGuild->getState() == Guild::GUILD_STATE_WAIT )
{
HashMapGuildMember& Members = pGuild->getMembers();
HashMapGuildMemberItor itr = Members.begin();
Statement* pStmt = NULL;
Result* pResult = NULL;
BEGIN_DB
{
pStmt = g_pDatabaseManager->getConnection("DARKEDEN" )->createStatement();
for (; itr != Members.end(); itr++ )
{
GuildMember* pGuildMember = itr->second;
// ์ ์ํด ์์ผ๋ฉด
__ENTER_CRITICAL_SECTION((*g_pPCFinder))
Creature* pCreature = g_pPCFinder->getCreature_LOCKED(pGuildMember->getName());
if (pCreature != NULL && pCreature->isPC() )
{
Player* pPlayer = pCreature->getPlayer();
Assert(pPlayer != NULL);
PlayerCreature* pPlayerCreature = dynamic_cast<PlayerCreature*>(pCreature);
Assert(pPlayerCreature != NULL);
// ๋ฑ๋ก๋น๋ฅผ ํ๋ถํ๋ค.
Gold_t Gold = pPlayerCreature->getGold();
if (pGuildMember->getRank() == GuildMember::GUILDMEMBER_RANK_MASTER )
{
Gold = min((uint64_t)(Gold + RETURN_SLAYER_MASTER_GOLD), (uint64_t)2000000000);
}
else if (pGuildMember->getRank() == GuildMember::GUILDMEMBER_RANK_SUBMASTER )
{
Gold = min((uint64_t)(Gold + RETURN_SLAYER_SUBMASTER_GOLD), (uint64_t)2000000000);
}
pPlayerCreature->setGoldEx(Gold);
GCModifyInformation gcModifyInformation;
gcModifyInformation.addLongData(MODIFY_GOLD, Gold);
pPlayer->sendPacket(&gcModifyInformation);
// ๋ฉ์์ง๋ฅผ ๋ณด๋ธ๋ค.
pResult = pStmt->executeQuery("SELECT Message FROM Messages WHERE Receiver = '%s'", pCreature->getName().c_str());
while (pResult->next() )
{
GCSystemMessage message;
message.setMessage(pResult->getString(1));
pPlayer->sendPacket(&message);
}
pStmt->executeQuery("DELETE FROM Messages WHERE Receiver = '%s'", pCreature->getName().c_str());
}
__LEAVE_CRITICAL_SECTION((*g_pPCFinder))
// ๊ธธ๋ ๋ฉค๋ฒ ๊ฐ์ฒด๋ฅผ ์ญ์ ํ๋ค.
SAFE_DELETE(pGuildMember);
}
// ๊ธธ๋ ๋ฉค๋ฒ ํด์ฌ ๋งต์ ์ง์ด๋ค.
Members.clear();
// ๊ธธ๋ ๋งค๋์ ์์ ๊ธธ๋๋ฅผ ์ญ์ ํ๋ค.
g_pGuildManager->deleteGuild(pGuild->getID());
GuildUnionManager::Instance().removeMasterGuild(pGuild->getID());
// ๊ธธ๋ ๊ฐ์ฒด๋ฅผ ์ญ์ ํ๋ค.
SAFE_DELETE(pGuild);
SAFE_DELETE(pStmt);
}
END_DB(pStmt)
}
#endif
__END_CATCH
}
| [
"tiancaiamao@gmail.com"
] | tiancaiamao@gmail.com |
069b1a015e7b9122da83a67f95846c3e6a052412 | 891f40044ffc2133a2d8f56e19d4057648c81a99 | /C++/Estruturas de Repetiรงรฃo/While.cpp | 05a62c176f3587755fd77aa5a1cfaa79acd952d6 | [] | no_license | mat-garcia/Estudos | bb7b83e2f31cc79563d0deac26fe58efcea5c6f0 | 0c697e0e6627552ab9366b03353766153ba30d38 | refs/heads/main | 2023-05-31T05:11:34.897645 | 2021-06-05T02:15:18 | 2021-06-05T02:15:18 | 371,191,086 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 178 | cpp | #include <iostream>
using namespace std;
int main()
{
int num ;
num=10 ;
while (num<=100)
{
cout << num << "\n" ;
num++;
}
} | [
"noreply@github.com"
] | mat-garcia.noreply@github.com |
1e9c6062d208c8264a794c563f62ed2bf94c5d7b | 26393ea905a8fbbfd674abf582a51cf227e7a878 | /chrome/browser/ui/webui/media_router/media_router_webui_message_handler_unittest.cc | c61899374148a8d6f0c64499819d248153a6ce57 | [
"BSD-3-Clause"
] | permissive | shockerjue/chromium | c920f7196c5e12fc918664ad9807ff584c7384f0 | ec2d4ae90a08738eb616bb2ab1c0fee5a551e0d6 | refs/heads/master | 2023-01-07T02:07:00.864783 | 2018-04-28T12:29:23 | 2018-04-28T12:29:23 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 27,738 | cc | // Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/ui/webui/media_router/media_router_webui_message_handler.h"
#include <memory>
#include "base/macros.h"
#include "base/strings/stringprintf.h"
#include "chrome/browser/media/router/test/media_router_mojo_test.h"
#include "chrome/browser/media/router/test/mock_media_router.h"
#include "chrome/browser/ui/browser_commands.h"
#include "chrome/browser/ui/tabs/tab_strip_model.h"
#include "chrome/browser/ui/webui/media_router/media_router_ui.h"
#include "chrome/browser/ui/webui/media_router/media_router_web_ui_test.h"
#include "content/public/browser/browser_context.h"
#include "content/public/test/test_web_ui.h"
#include "extensions/common/constants.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
using testing::_;
using testing::Return;
using testing::ReturnRef;
namespace media_router {
namespace {
const char kUserEmailForTesting[] = "nobody@example.com";
const char kUserDomainForTesting[] = "example.com";
bool GetBooleanFromDict(const base::DictionaryValue* dict,
const std::string& key) {
bool value = false;
EXPECT_TRUE(dict->GetBoolean(key, &value));
return value;
}
double GetDoubleFromDict(const base::DictionaryValue* dict,
const std::string& key) {
double value = 0;
EXPECT_TRUE(dict->GetDouble(key, &value));
return value;
}
int GetIntegerFromDict(const base::DictionaryValue* dict,
const std::string& key) {
int value = 0;
EXPECT_TRUE(dict->GetInteger(key, &value));
return value;
}
std::string GetStringFromDict(const base::DictionaryValue* dict,
const std::string& key) {
std::string value;
EXPECT_TRUE(dict->GetString(key, &value));
return value;
}
// Creates a local route for display.
MediaRoute CreateRoute() {
MediaRoute::Id route_id("routeId123");
MediaSink::Id sink_id("sinkId123");
MediaSink sink(sink_id, "The sink", SinkIconType::CAST);
std::string description("This is a route");
bool is_local = true;
bool is_for_display = true;
MediaRoute route(route_id, MediaSource("mediaSource"), sink_id, description,
is_local, is_for_display);
return route;
}
MediaSinkWithCastModes CreateMediaSinkWithCastMode(const std::string& sink_id,
MediaCastMode cast_mode) {
std::string sink_name("The sink");
MediaSinkWithCastModes media_sink_with_cast_modes(
MediaSink(sink_id, sink_name, SinkIconType::CAST));
media_sink_with_cast_modes.cast_modes.insert(cast_mode);
return media_sink_with_cast_modes;
}
} // namespace
class MockMediaRouterUI : public MediaRouterUI {
public:
explicit MockMediaRouterUI(content::WebUI* web_ui)
: MediaRouterUI(web_ui) {}
~MockMediaRouterUI() override {}
MOCK_METHOD0(UIInitialized, void());
MOCK_CONST_METHOD0(UserSelectedTabMirroringForCurrentOrigin, bool());
MOCK_METHOD1(RecordCastModeSelection, void(MediaCastMode cast_mode));
MOCK_CONST_METHOD0(cast_modes, const std::set<MediaCastMode>&());
MOCK_METHOD1(OnMediaControllerUIAvailable,
void(const MediaRoute::Id& route_id));
MOCK_METHOD0(OnMediaControllerUIClosed, void());
MOCK_METHOD0(PlayRoute, void());
MOCK_METHOD0(PauseRoute, void());
MOCK_METHOD1(SeekRoute, void(base::TimeDelta time));
MOCK_METHOD1(SetRouteMute, void(bool mute));
MOCK_METHOD1(SetRouteVolume, void(float volume));
MOCK_CONST_METHOD0(GetMediaRouteController, MediaRouteController*());
};
class TestMediaRouterWebUIMessageHandler
: public MediaRouterWebUIMessageHandler {
public:
explicit TestMediaRouterWebUIMessageHandler(MediaRouterUI* media_router_ui)
: MediaRouterWebUIMessageHandler(media_router_ui),
email_(kUserEmailForTesting),
domain_(kUserDomainForTesting) {}
~TestMediaRouterWebUIMessageHandler() override = default;
AccountInfo GetAccountInfo() override {
AccountInfo info = AccountInfo();
info.account_id = info.gaia = info.email = email_;
info.hosted_domain = domain_;
info.full_name = info.given_name = "name";
info.locale = "locale";
info.picture_url = "picture";
return info;
}
void SetEmailAndDomain(const std::string& email, const std::string& domain) {
email_ = email;
domain_ = domain;
}
private:
std::string email_;
std::string domain_;
};
class MediaRouterWebUIMessageHandlerTest : public MediaRouterWebUITest {
public:
MediaRouterWebUIMessageHandlerTest()
: web_ui_(std::make_unique<content::TestWebUI>()) {}
~MediaRouterWebUIMessageHandlerTest() override {}
// BrowserWithTestWindowTest:
void SetUp() override {
BrowserWithTestWindowTest::SetUp();
chrome::NewTab(browser());
web_ui_->set_web_contents(
browser()->tab_strip_model()->GetActiveWebContents());
mock_media_router_ui_ = std::make_unique<MockMediaRouterUI>(web_ui_.get());
handler_ = std::make_unique<TestMediaRouterWebUIMessageHandler>(
mock_media_router_ui_.get());
handler_->SetWebUIForTest(web_ui_.get());
}
void TearDown() override {
handler_.reset();
mock_media_router_ui_.reset();
web_ui_.reset();
BrowserWithTestWindowTest::TearDown();
}
const std::string& provider_extension_id() const {
return provider_extension_id_;
}
// Gets the call data for the function call made to |web_ui_|. There needs
// to be one call made, and its function name must be |function_name|.
const base::Value* GetCallData(const std::string& function_name) {
CHECK(1u == web_ui_->call_data().size());
const content::TestWebUI::CallData& call_data = *web_ui_->call_data()[0];
CHECK(function_name == call_data.function_name());
return call_data.arg1();
}
// Gets the dictionary passed into a call to the |web_ui_| as the argument.
// There needs to be one call made, and its function name must be
// |function_name|.
const base::DictionaryValue* ExtractDictFromCallArg(
const std::string& function_name) {
const base::DictionaryValue* dict_value = nullptr;
CHECK(GetCallData(function_name)->GetAsDictionary(&dict_value));
return dict_value;
}
// Gets the list passed into a call to the |web_ui_| as the argument.
// There needs to be one call made, and its function name must be
// |function_name|.
const base::ListValue* ExtractListFromCallArg(
const std::string& function_name) {
const base::ListValue* list_value = nullptr;
CHECK(GetCallData(function_name)->GetAsList(&list_value));
return list_value;
}
// Gets the first element of the list passed in as the argument to a call to
// the |web_ui_| as a dictionary. There needs to be one call made, and its
// function name must be |function_name|.
const base::DictionaryValue* ExtractDictFromListFromCallArg(
const std::string& function_name) {
const base::ListValue* list_value = nullptr;
CHECK(GetCallData(function_name)->GetAsList(&list_value));
const base::DictionaryValue* dict_value = nullptr;
CHECK(list_value->GetDictionary(0, &dict_value));
return dict_value;
}
MockMediaRouter* router() { return &router_; }
protected:
std::unique_ptr<content::TestWebUI> web_ui_;
MockMediaRouter router_;
std::unique_ptr<MockMediaRouterUI> mock_media_router_ui_;
std::unique_ptr<TestMediaRouterWebUIMessageHandler> handler_;
const std::string provider_extension_id_;
};
TEST_F(MediaRouterWebUIMessageHandlerTest, UpdateSinks) {
MediaSink::Id sink_id("sinkId123");
MediaSinkWithCastModes media_sink_with_cast_modes =
CreateMediaSinkWithCastMode(sink_id, MediaCastMode::TAB_MIRROR);
handler_->UpdateSinks({media_sink_with_cast_modes});
const base::DictionaryValue* sinks_with_identity_value =
ExtractDictFromCallArg("media_router.ui.setSinkListAndIdentity");
// Email is not displayed if there is no sinks with domain.
EXPECT_FALSE(GetBooleanFromDict(sinks_with_identity_value, "showEmail"));
// Domain is not displayed if there is no sinks with domain.
EXPECT_FALSE(GetBooleanFromDict(sinks_with_identity_value, "showDomain"));
const base::ListValue* sinks_list_value = nullptr;
ASSERT_TRUE(sinks_with_identity_value->GetList("sinks", &sinks_list_value));
const base::DictionaryValue* sink_value = nullptr;
ASSERT_TRUE(sinks_list_value->GetDictionary(0, &sink_value));
EXPECT_EQ(sink_id, GetStringFromDict(sink_value, "id"));
EXPECT_EQ(media_sink_with_cast_modes.sink.name(),
GetStringFromDict(sink_value, "name"));
EXPECT_EQ(static_cast<int>(MediaCastMode::TAB_MIRROR),
GetIntegerFromDict(sink_value, "castModes"));
}
TEST_F(MediaRouterWebUIMessageHandlerTest, UpdateSinksWithIdentity) {
MediaSinkWithCastModes media_sink_with_cast_modes =
CreateMediaSinkWithCastMode("sinkId123", MediaCastMode::TAB_MIRROR);
media_sink_with_cast_modes.sink.set_domain(kUserDomainForTesting);
handler_->UpdateSinks({media_sink_with_cast_modes});
const base::DictionaryValue* sinks_with_identity_value =
ExtractDictFromCallArg("media_router.ui.setSinkListAndIdentity");
EXPECT_TRUE(GetBooleanFromDict(sinks_with_identity_value, "showEmail"));
// Sink domain is not displayed if it matches user domain.
EXPECT_FALSE(GetBooleanFromDict(sinks_with_identity_value, "showDomain"));
EXPECT_EQ(kUserEmailForTesting,
GetStringFromDict(sinks_with_identity_value, "userEmail"));
}
TEST_F(MediaRouterWebUIMessageHandlerTest,
UpdateSinksWithIdentityAndPseudoSink) {
MediaSinkWithCastModes media_sink_with_cast_modes =
CreateMediaSinkWithCastMode("pseudo:sinkId1", MediaCastMode::TAB_MIRROR);
media_sink_with_cast_modes.sink.set_domain(kUserDomainForTesting);
handler_->UpdateSinks({media_sink_with_cast_modes});
const base::DictionaryValue* sinks_with_identity_value =
ExtractDictFromCallArg("media_router.ui.setSinkListAndIdentity");
EXPECT_FALSE(GetBooleanFromDict(sinks_with_identity_value, "showEmail"));
}
TEST_F(MediaRouterWebUIMessageHandlerTest, UpdateSinksWithIdentityAndDomain) {
MediaSinkWithCastModes media_sink_with_cast_modes =
CreateMediaSinkWithCastMode("sinkId123", MediaCastMode::TAB_MIRROR);
std::string domain_name("google.com");
media_sink_with_cast_modes.sink.set_domain(domain_name);
handler_->UpdateSinks({media_sink_with_cast_modes});
const base::DictionaryValue* sinks_with_identity_value =
ExtractDictFromCallArg("media_router.ui.setSinkListAndIdentity");
// Domain is displayed for sinks with domains that are not the user domain.
EXPECT_TRUE(GetBooleanFromDict(sinks_with_identity_value, "showDomain"));
}
TEST_F(MediaRouterWebUIMessageHandlerTest, UpdateSinksWithNoDomain) {
MediaSinkWithCastModes media_sink_with_cast_modes =
CreateMediaSinkWithCastMode("sinkId123", MediaCastMode::TAB_MIRROR);
std::string user_email("nobody@gmail.com");
std::string user_domain("NO_HOSTED_DOMAIN");
std::string domain_name("default");
media_sink_with_cast_modes.sink.set_domain(domain_name);
handler_->SetEmailAndDomain(user_email, user_domain);
handler_->UpdateSinks({media_sink_with_cast_modes});
const base::DictionaryValue* sinks_with_identity_value =
ExtractDictFromCallArg("media_router.ui.setSinkListAndIdentity");
const base::ListValue* sinks_list_value = nullptr;
ASSERT_TRUE(sinks_with_identity_value->GetList("sinks", &sinks_list_value));
const base::DictionaryValue* sink_value = nullptr;
ASSERT_TRUE(sinks_list_value->GetDictionary(0, &sink_value));
// Domain should not be shown if there were only default sink domains.
EXPECT_FALSE(GetBooleanFromDict(sinks_with_identity_value, "showDomain"));
// Sink domain should be empty if user has no hosted domain.
EXPECT_EQ(std::string(), GetStringFromDict(sink_value, "domain"));
}
TEST_F(MediaRouterWebUIMessageHandlerTest, UpdateSinksWithDefaultDomain) {
MediaSinkWithCastModes media_sink_with_cast_modes =
CreateMediaSinkWithCastMode("sinkId123", MediaCastMode::TAB_MIRROR);
std::string domain_name("default");
media_sink_with_cast_modes.sink.set_domain(domain_name);
handler_->UpdateSinks({media_sink_with_cast_modes});
const base::DictionaryValue* sinks_with_identity_value =
ExtractDictFromCallArg("media_router.ui.setSinkListAndIdentity");
const base::ListValue* sinks_list_value = nullptr;
ASSERT_TRUE(sinks_with_identity_value->GetList("sinks", &sinks_list_value));
const base::DictionaryValue* sink_value = nullptr;
ASSERT_TRUE(sinks_list_value->GetDictionary(0, &sink_value));
// Domain should not be shown if there were only default sink domains.
EXPECT_FALSE(GetBooleanFromDict(sinks_with_identity_value, "showDomain"));
// Sink domain should be updated from 'default' to user domain.
EXPECT_EQ(kUserDomainForTesting, GetStringFromDict(sink_value, "domain"));
}
TEST_F(MediaRouterWebUIMessageHandlerTest, UpdateRoutes) {
const MediaRoute route = CreateRoute();
std::vector<MediaRoute::Id> joinable_route_ids = {route.media_route_id()};
std::unordered_map<MediaRoute::Id, MediaCastMode> current_cast_modes;
current_cast_modes.insert(
std::make_pair(route.media_route_id(), MediaCastMode::PRESENTATION));
handler_->UpdateRoutes({route}, joinable_route_ids, current_cast_modes);
const base::DictionaryValue* route_value =
ExtractDictFromListFromCallArg("media_router.ui.setRouteList");
EXPECT_EQ(route.media_route_id(), GetStringFromDict(route_value, "id"));
EXPECT_EQ(route.media_sink_id(), GetStringFromDict(route_value, "sinkId"));
EXPECT_EQ(route.description(), GetStringFromDict(route_value, "description"));
EXPECT_EQ(route.is_local(), GetBooleanFromDict(route_value, "isLocal"));
EXPECT_TRUE(GetBooleanFromDict(route_value, "canJoin"));
EXPECT_EQ(MediaCastMode::PRESENTATION,
GetIntegerFromDict(route_value, "currentCastMode"));
}
TEST_F(MediaRouterWebUIMessageHandlerTest, UpdateRoutesIncognito) {
handler_->set_incognito_for_test(true);
const MediaRoute route = CreateRoute();
handler_->UpdateRoutes({route}, std::vector<MediaRoute::Id>(),
std::unordered_map<MediaRoute::Id, MediaCastMode>());
const base::DictionaryValue* route_value =
ExtractDictFromListFromCallArg("media_router.ui.setRouteList");
EXPECT_EQ(route.media_route_id(), GetStringFromDict(route_value, "id"));
EXPECT_EQ(route.media_sink_id(), GetStringFromDict(route_value, "sinkId"));
EXPECT_EQ(route.description(), GetStringFromDict(route_value, "description"));
EXPECT_EQ(route.is_local(), GetBooleanFromDict(route_value, "isLocal"));
EXPECT_FALSE(GetBooleanFromDict(route_value, "canJoin"));
int actual_current_cast_mode = -1;
EXPECT_FALSE(
route_value->GetInteger("currentCastMode", &actual_current_cast_mode));
}
TEST_F(MediaRouterWebUIMessageHandlerTest, SetCastModesList) {
CastModeSet cast_modes({MediaCastMode::PRESENTATION,
MediaCastMode::TAB_MIRROR,
MediaCastMode::DESKTOP_MIRROR});
handler_->UpdateCastModes(cast_modes, "www.host.com",
MediaCastMode::PRESENTATION);
const base::ListValue* set_cast_mode_list =
ExtractListFromCallArg("media_router.ui.setCastModeList");
const base::DictionaryValue* cast_mode = nullptr;
size_t index = 0;
for (auto i = cast_modes.begin(); i != cast_modes.end(); i++) {
CHECK(set_cast_mode_list->GetDictionary(index++, &cast_mode));
EXPECT_EQ(static_cast<int>(*i), GetIntegerFromDict(cast_mode, "type"));
EXPECT_EQ(MediaCastModeToDescription(*i, "www.host.com"),
GetStringFromDict(cast_mode, "description"));
EXPECT_EQ("www.host.com", GetStringFromDict(cast_mode, "host"));
EXPECT_EQ(*i == MediaCastMode::PRESENTATION,
GetBooleanFromDict(cast_mode, "isForced"));
}
}
TEST_F(MediaRouterWebUIMessageHandlerTest, UpdateMediaRouteStatus) {
MediaStatus status;
status.title = "test title";
status.can_play_pause = true;
status.can_set_volume = true;
status.play_state = MediaStatus::PlayState::BUFFERING;
status.duration = base::TimeDelta::FromSeconds(90);
status.current_time = base::TimeDelta::FromSeconds(80);
status.volume = 0.9;
// |status.hangouts_extra_data->local_present| defaults to |false|.
status.hangouts_extra_data.emplace();
status.mirroring_extra_data.emplace(true);
handler_->UpdateMediaRouteStatus(status);
const base::DictionaryValue* status_value =
ExtractDictFromCallArg("media_router.ui.updateRouteStatus");
EXPECT_EQ(status.title, GetStringFromDict(status_value, "title"));
EXPECT_EQ(status.can_play_pause,
GetBooleanFromDict(status_value, "canPlayPause"));
EXPECT_EQ(status.can_mute, GetBooleanFromDict(status_value, "canMute"));
EXPECT_EQ(status.can_set_volume,
GetBooleanFromDict(status_value, "canSetVolume"));
EXPECT_EQ(status.can_seek, GetBooleanFromDict(status_value, "canSeek"));
EXPECT_EQ(static_cast<int>(status.play_state),
GetIntegerFromDict(status_value, "playState"));
EXPECT_EQ(status.is_muted, GetBooleanFromDict(status_value, "isMuted"));
EXPECT_EQ(status.duration.InSeconds(),
GetIntegerFromDict(status_value, "duration"));
EXPECT_EQ(status.current_time.InSeconds(),
GetIntegerFromDict(status_value, "currentTime"));
EXPECT_EQ(status.volume, GetDoubleFromDict(status_value, "volume"));
const base::Value* hangouts_extra_data = status_value->FindKeyOfType(
"hangoutsExtraData", base::Value::Type::DICTIONARY);
ASSERT_TRUE(hangouts_extra_data);
const base::Value* local_present_value = hangouts_extra_data->FindKeyOfType(
"localPresent", base::Value::Type::BOOLEAN);
ASSERT_TRUE(local_present_value);
EXPECT_FALSE(local_present_value->GetBool());
const base::Value* mirroring_extra_data = status_value->FindKeyOfType(
"mirroringExtraData", base::Value::Type::DICTIONARY);
ASSERT_TRUE(mirroring_extra_data);
const base::Value* media_remoting_value = mirroring_extra_data->FindKeyOfType(
"mediaRemotingEnabled", base::Value::Type::BOOLEAN);
ASSERT_TRUE(media_remoting_value);
EXPECT_TRUE(media_remoting_value->GetBool());
}
TEST_F(MediaRouterWebUIMessageHandlerTest, OnCreateRouteResponseReceived) {
MediaRoute route = CreateRoute();
bool incognito = false;
route.set_incognito(incognito);
handler_->OnCreateRouteResponseReceived(route.media_sink_id(), &route);
const content::TestWebUI::CallData& call_data = *web_ui_->call_data()[0];
EXPECT_EQ("media_router.ui.onCreateRouteResponseReceived",
call_data.function_name());
std::string sink_id_value;
ASSERT_TRUE(call_data.arg1()->GetAsString(&sink_id_value));
EXPECT_EQ(route.media_sink_id(), sink_id_value);
const base::DictionaryValue* route_value = nullptr;
ASSERT_TRUE(call_data.arg2()->GetAsDictionary(&route_value));
EXPECT_EQ(route.media_route_id(), GetStringFromDict(route_value, "id"));
EXPECT_EQ(route.media_sink_id(), GetStringFromDict(route_value, "sinkId"));
EXPECT_EQ(route.description(), GetStringFromDict(route_value, "description"));
EXPECT_EQ(route.is_local(), GetBooleanFromDict(route_value, "isLocal"));
bool route_for_display = false;
ASSERT_TRUE(call_data.arg3()->GetAsBoolean(&route_for_display));
EXPECT_TRUE(route_for_display);
}
TEST_F(MediaRouterWebUIMessageHandlerTest,
OnCreateRouteResponseReceivedIncognito) {
handler_->set_incognito_for_test(true);
MediaRoute route = CreateRoute();
bool incognito = true;
route.set_incognito(incognito);
handler_->OnCreateRouteResponseReceived(route.media_sink_id(), &route);
const content::TestWebUI::CallData& call_data = *web_ui_->call_data()[0];
EXPECT_EQ("media_router.ui.onCreateRouteResponseReceived",
call_data.function_name());
std::string sink_id_value;
ASSERT_TRUE(call_data.arg1()->GetAsString(&sink_id_value));
EXPECT_EQ(route.media_sink_id(), sink_id_value);
const base::DictionaryValue* route_value = nullptr;
ASSERT_TRUE(call_data.arg2()->GetAsDictionary(&route_value));
EXPECT_EQ(route.media_route_id(), GetStringFromDict(route_value, "id"));
EXPECT_EQ(route.media_sink_id(), GetStringFromDict(route_value, "sinkId"));
EXPECT_EQ(route.description(), GetStringFromDict(route_value, "description"));
EXPECT_EQ(route.is_local(), GetBooleanFromDict(route_value, "isLocal"));
bool route_for_display = false;
ASSERT_TRUE(call_data.arg3()->GetAsBoolean(&route_for_display));
EXPECT_TRUE(route_for_display);
}
TEST_F(MediaRouterWebUIMessageHandlerTest, UpdateIssue) {
std::string issue_title("An issue");
std::string issue_message("This is an issue");
IssueInfo::Action default_action = IssueInfo::Action::LEARN_MORE;
std::vector<IssueInfo::Action> secondary_actions;
secondary_actions.push_back(IssueInfo::Action::DISMISS);
MediaRoute::Id route_id("routeId123");
IssueInfo info(issue_title, default_action, IssueInfo::Severity::FATAL);
info.message = issue_message;
info.secondary_actions = secondary_actions;
info.route_id = route_id;
Issue issue(info);
const Issue::Id& issue_id = issue.id();
handler_->UpdateIssue(issue);
const base::DictionaryValue* issue_value =
ExtractDictFromCallArg("media_router.ui.setIssue");
// Initialized to invalid issue id.
EXPECT_EQ(issue_id, GetIntegerFromDict(issue_value, "id"));
EXPECT_EQ(issue_title, GetStringFromDict(issue_value, "title"));
EXPECT_EQ(issue_message, GetStringFromDict(issue_value, "message"));
// Initialized to invalid action type.
EXPECT_EQ(static_cast<int>(default_action),
GetIntegerFromDict(issue_value, "defaultActionType"));
EXPECT_EQ(static_cast<int>(secondary_actions[0]),
GetIntegerFromDict(issue_value, "secondaryActionType"));
EXPECT_EQ(route_id, GetStringFromDict(issue_value, "routeId"));
// The issue is blocking since it is FATAL.
EXPECT_TRUE(GetBooleanFromDict(issue_value, "isBlocking"));
}
TEST_F(MediaRouterWebUIMessageHandlerTest, RecordCastModeSelection) {
base::ListValue args;
args.AppendInteger(MediaCastMode::PRESENTATION);
EXPECT_CALL(*mock_media_router_ui_,
RecordCastModeSelection(MediaCastMode::PRESENTATION))
.Times(1);
handler_->OnReportSelectedCastMode(&args);
args.Clear();
args.AppendInteger(MediaCastMode::TAB_MIRROR);
EXPECT_CALL(*mock_media_router_ui_,
RecordCastModeSelection(MediaCastMode::TAB_MIRROR))
.Times(1);
handler_->OnReportSelectedCastMode(&args);
}
TEST_F(MediaRouterWebUIMessageHandlerTest, RetrieveCastModeSelection) {
base::ListValue args;
std::set<MediaCastMode> cast_modes = {MediaCastMode::TAB_MIRROR};
EXPECT_CALL(*mock_media_router_ui_, cast_modes())
.WillRepeatedly(ReturnRef(cast_modes));
EXPECT_CALL(*mock_media_router_ui_,
UserSelectedTabMirroringForCurrentOrigin())
.WillOnce(Return(true));
handler_->OnRequestInitialData(&args);
const content::TestWebUI::CallData& call_data1 = *web_ui_->call_data()[0];
ASSERT_EQ("media_router.ui.setInitialData", call_data1.function_name());
const base::DictionaryValue* initial_data = nullptr;
ASSERT_TRUE(call_data1.arg1()->GetAsDictionary(&initial_data));
EXPECT_TRUE(GetBooleanFromDict(initial_data, "useTabMirroring"));
EXPECT_CALL(*mock_media_router_ui_,
UserSelectedTabMirroringForCurrentOrigin())
.WillOnce(Return(false));
handler_->OnRequestInitialData(&args);
const content::TestWebUI::CallData& call_data2 = *web_ui_->call_data()[1];
ASSERT_EQ("media_router.ui.setInitialData", call_data2.function_name());
ASSERT_TRUE(call_data2.arg1()->GetAsDictionary(&initial_data));
EXPECT_FALSE(GetBooleanFromDict(initial_data, "useTabMirroring"));
}
TEST_F(MediaRouterWebUIMessageHandlerTest, OnRouteDetailsOpenedAndClosed) {
const std::string route_id = "routeId123";
base::ListValue args_list;
base::DictionaryValue* args;
args_list.Append(std::make_unique<base::DictionaryValue>());
args_list.GetDictionary(0, &args);
args->SetString("routeId", route_id);
EXPECT_CALL(*mock_media_router_ui_, OnMediaControllerUIAvailable(route_id));
handler_->OnMediaControllerAvailable(&args_list);
args_list.Clear();
EXPECT_CALL(*mock_media_router_ui_, OnMediaControllerUIClosed());
handler_->OnMediaControllerClosed(&args_list);
}
TEST_F(MediaRouterWebUIMessageHandlerTest, OnMediaCommandsReceived) {
auto controller = base::MakeRefCounted<MockMediaRouteController>(
"routeId", profile(), router());
EXPECT_CALL(*mock_media_router_ui_, GetMediaRouteController())
.WillRepeatedly(Return(controller.get()));
MediaStatus status;
status.duration = base::TimeDelta::FromSeconds(100);
handler_->UpdateMediaRouteStatus(status);
base::ListValue args_list;
EXPECT_CALL(*controller, Play());
handler_->OnPlayCurrentMedia(&args_list);
EXPECT_CALL(*controller, Pause());
handler_->OnPauseCurrentMedia(&args_list);
base::DictionaryValue* args;
args_list.Append(std::make_unique<base::DictionaryValue>());
args_list.GetDictionary(0, &args);
const int time = 50;
args->SetInteger("time", time);
EXPECT_CALL(*controller, Seek(base::TimeDelta::FromSeconds(time)));
handler_->OnSeekCurrentMedia(&args_list);
args->Clear();
args->SetBoolean("mute", true);
EXPECT_CALL(*controller, SetMute(true));
handler_->OnSetCurrentMediaMute(&args_list);
const double volume = 0.4;
args->Clear();
args->SetDouble("volume", volume);
EXPECT_CALL(*controller, SetVolume(volume));
handler_->OnSetCurrentMediaVolume(&args_list);
}
TEST_F(MediaRouterWebUIMessageHandlerTest, OnSetMediaRemotingEnabled) {
auto controller = base::MakeRefCounted<MirroringMediaRouteController>(
"routeId", profile(), router());
EXPECT_CALL(*mock_media_router_ui_, GetMediaRouteController())
.WillRepeatedly(Return(controller.get()));
base::ListValue args_list;
args_list.GetList().emplace_back(false);
handler_->OnSetMediaRemotingEnabled(&args_list);
EXPECT_FALSE(controller->media_remoting_enabled());
}
TEST_F(MediaRouterWebUIMessageHandlerTest, OnInvalidMediaCommandsReceived) {
auto controller = base::MakeRefCounted<MockMediaRouteController>(
"routeId", profile(), router());
EXPECT_CALL(*mock_media_router_ui_, GetMediaRouteController())
.WillRepeatedly(Return(controller.get()));
MediaStatus status;
status.duration = base::TimeDelta::FromSeconds(100);
handler_->UpdateMediaRouteStatus(status);
EXPECT_CALL(*controller, Seek(_)).Times(0);
EXPECT_CALL(*controller, SetVolume(_)).Times(0);
base::ListValue args_list;
base::DictionaryValue* args;
args_list.Append(std::make_unique<base::DictionaryValue>());
args_list.GetDictionary(0, &args);
// Seek positions greater than the duration or negative should be ignored.
args->SetInteger("time", 101);
handler_->OnSeekCurrentMedia(&args_list);
args->SetInteger("time", -10);
handler_->OnSeekCurrentMedia(&args_list);
args->Clear();
// Volumes outside of the [0, 1] range should be ignored.
args->SetDouble("volume", 1.5);
handler_->OnSetCurrentMediaVolume(&args_list);
args->SetDouble("volume", 1.5);
handler_->OnSetCurrentMediaVolume(&args_list);
}
TEST_F(MediaRouterWebUIMessageHandlerTest, OnRouteControllerInvalidated) {
handler_->OnRouteControllerInvalidated();
EXPECT_EQ(1u, web_ui_->call_data().size());
const content::TestWebUI::CallData& call_data = *web_ui_->call_data()[0];
EXPECT_EQ("media_router.ui.onRouteControllerInvalidated",
call_data.function_name());
}
} // namespace media_router
| [
"commit-bot@chromium.org"
] | commit-bot@chromium.org |
784c72b3dfe24e5cd3b9e4e4163bfe7676a6e922 | 2f99ff7c32c5478676f57318387b80182a5aba85 | /src/utilities/macros.cpp | ba6a7cffc4e3d5c33082c86c57d1c9baf24b74db | [] | no_license | vesuppi/LinearC | 5fb4dd10afccd49312bad3557e7b123b63be8612 | 832dbc9254fd9baf67a9a6786e884dee5453bd0a | refs/heads/master | 2021-09-03T12:00:25.763294 | 2018-01-08T22:54:50 | 2018-01-08T22:54:50 | 94,836,770 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 67 | cpp | //
// Created by GentlyGuitar on 6/6/2017.
//
#include "macros.h"
| [
"zt9465@gmail.com"
] | zt9465@gmail.com |
d2311347e04fa52fe81e19b38242bdcd30b4e1dd | 558735d53c3df6abda3dddd4408c60351a57b34b | /Unit 07 - Object oriented programming with classes/07Ce - Class Inheritance/MultipleChoiceQuestion.cpp | aac1d4b2445bba4b81ce30a7e1ee40806993a9e5 | [] | no_license | michaelswright/CS200 | 139840a314c5d66b433ab32ecf5b832ec4830cc6 | 84b460f267399d7ee45dcf11ca86eee3ed610735 | refs/heads/main | 2023-05-26T08:04:42.756252 | 2021-06-14T22:34:01 | 2021-06-14T22:34:01 | 376,969,920 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 726 | cpp | #include "MultipleChoiceQuestion.hpp"
#include <iostream>
#include "Question.hpp"
using namespace std;
void MultipleChoiceQuestion::SetAnswers(string answers[4], int correctIndex)
{
m_correctIndex = correctIndex;
for (int i = 0; i < 4; i++)
{
m_answers[i] = answers[i];
}
}
bool MultipleChoiceQuestion::AskQuestion()
{
int answer;
DisplayQuestion();
for (int i = 0; i < 4; i++)
{
cout << i << ". " << m_answers[i] << endl;
}
cout << "Your answer: ";
cin.ignore();
cin >> answer;
if (answer == m_correctIndex)
{
cout << "Correct!" << endl;
return true;
}
else
{
cout << "Wrong!" << endl;
return false;
}
} | [
"8026090-mswright@users.noreply.gitlab.com"
] | 8026090-mswright@users.noreply.gitlab.com |
0e06cae433db988aafc3f6f75e0d4e81c39d4b65 | 0ebb297fe3a7354d988661be5b1de8ab2019c60a | /code/neuroevo/webinterface/rtp_interface/params/fixed_or_random_par.cpp | 68fb242a90fe8779094e32dcf55c0d2cfe215889 | [] | no_license | kamrann/workbase | a56e8ca3874ae5e71e4c77331ed10f59acff5914 | ce2cade80365f885839bf96bfc5db5e57059ba39 | refs/heads/master | 2021-01-19T03:22:32.745349 | 2015-01-02T23:05:04 | 2015-01-02T23:05:04 | 15,985,205 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,378 | cpp | // fixed_or_random_par.cpp
#include "fixed_or_random_par.h"
#include "realnum_par.h"
#include "../rtp_param_widget.h"
#include "../rtp_defs.h"
#include <Wt/WComboBox>
#include <Wt/WText>
#include <Wt/WHBoxLayout>
#include <boost/random/uniform_real_distribution.hpp>
i_param_widget* rtp_fixed_or_random_param_type::create_widget(rtp_param_manager* mgr) const
{
rtp_param_widget< Wt::WContainerWidget >* widget = new rtp_param_widget< Wt::WContainerWidget >(this);
Wt::WHBoxLayout* layout = new Wt::WHBoxLayout();
layout->setContentsMargins(0, 0, 0, 0);
widget->setLayout(layout);
Wt::WComboBox* box = new Wt::WComboBox();
box->addItem("Fixed");
box->addItem("Random");
// box->setMinimumSize(75, Wt::WLength::Auto);
layout->addWidget(box);
rtp_realnum_param_type* fixed_pt = new rtp_realnum_param_type(m_default, m_min, m_max);
//fixed_pt->use_spin(true, )
i_param_widget* fixed = fixed_pt->create_widget(mgr);
// fixed->get_wt_widget()->setMinimumSize(75, Wt::WLength::Auto);
layout->addWidget(fixed->get_wt_widget());
Wt::WText* txt = new Wt::WText("[");
// txt->setMinimumSize(15, Wt::WLength::Auto);
layout->addWidget(txt);
i_param_widget* rand_min = (new rtp_realnum_param_type(m_default_min, m_min, m_max))->create_widget(mgr);
// rand_min->get_wt_widget()->setMinimumSize(75, Wt::WLength::Auto);
layout->addWidget(rand_min->get_wt_widget());
i_param_widget* rand_max = (new rtp_realnum_param_type(m_default_max, m_min, m_max))->create_widget(mgr);
// rand_max->get_wt_widget()->setMinimumSize(75, Wt::WLength::Auto);
layout->addWidget(rand_max->get_wt_widget());
txt = new Wt::WText(")");
// txt->setMinimumSize(15, Wt::WLength::Auto);
layout->addWidget(txt);
box->changed().connect(std::bind([=](){
int index = box->currentIndex();
if(index == 0)
{
/* fixed->get_wt_widget()->setHidden(false);
rand_min->get_wt_widget()->setHidden(true);
rand_max->get_wt_widget()->setHidden(true);
*/
widget->widget(1)->setHidden(false);
for(size_t i = 2; i < widget->count(); ++i)
{
widget->widget(i)->setHidden(true);
}
}
else
{
/* fixed->get_wt_widget()->setHidden(true);
rand_min->get_wt_widget()->setHidden(false);
rand_max->get_wt_widget()->setHidden(false);
*/
widget->widget(1)->setHidden(true);
for(size_t i = 2; i < widget->count(); ++i)
{
widget->widget(i)->setHidden(false);
}
}
}));
box->changed().emit();
return widget;
}
rtp_param rtp_fixed_or_random_param_type::get_widget_param(i_param_widget const* w) const
{
Wt::WContainerWidget const* cont = (Wt::WContainerWidget const*)w->get_wt_widget();
Wt::WComboBox const* box = (Wt::WComboBox const*)cont->widget(0);
bool is_fixed = box->currentIndex() == 0;
if(is_fixed)
{
i_param_widget const* fixed = dynamic_cast<i_param_widget const*>(cont->widget(1));
return rtp_param(fixed_or_random< double, boost::random::uniform_real_distribution< double >, rgen_t >(
boost::any_cast<double>(fixed->get_param())));
}
else
{
i_param_widget const* rand_min = dynamic_cast<i_param_widget const*>(cont->widget(3));
i_param_widget const* rand_max = dynamic_cast<i_param_widget const*>(cont->widget(4));
return rtp_param(fixed_or_random< double, boost::random::uniform_real_distribution< double >, rgen_t >(
boost::any_cast<double>(rand_min->get_param()),
boost::any_cast<double>(rand_max->get_param())));
}
}
| [
"cjangus@gmail.com"
] | cjangus@gmail.com |
47d92633fe6272664d73dca8c0a397375cb89703 | 9ebaa750a89f9e4e0e7f638c4032cbfae767cc1e | /MyAladdin/Stick.cpp | 8b50ddc0b90eb78ced15705aaf15a320a1afcdaa | [] | no_license | huynhthanhnhan/GameMegaman | 349fc78441d4ac3e74bcf7dbb2185952ca3c1af2 | 4b92bbf4a661c8b1d9b4f7ba908f9aadae4df43e | refs/heads/master | 2020-04-07T04:20:30.180700 | 2018-11-18T05:29:59 | 2018-11-18T05:29:59 | 158,051,491 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,124 | cpp | ๏ปฟ#include "Stick.h"
#include"Aladdin.h"
Stick::Stick(int x, int y, int width, int height)
{
this->_type = Global::Enemy;
this->_width = width;
this->_height = height;
this->_x = x;
this->_y = y - _height;
this->_vx = this->_vy = 0;
this->LoadResource();
this->updateBody();
this->_id = Global::STICKITEM;
}
Stick::~Stick()
{
}
void Stick::update(float deltaTime)
{
if (this->GetCurrentFrame(Global::JumpRun) == 1 )
{
this->_sound = Sound::Instance();
this->_sound->play(SOUND_STICK);
}
if (this->_start)
this->UpdateRender(Global::JumpRun);
}
void Stick::render()
{
this->transform();
this->Render(Global::Right, Global::JumpRun, this->_transform._position);
}
Collision::ResultCollision Stick::processCollision(Object * obj)
{
WRect rect1;
if (obj->getId() == Global::ALADDIN)
rect1 = ((Aladdin*)obj)->getRectBound2();
else
rect1 = obj->getRectBound();
WRect rect2 = this->getRectBound();
float vx1 = obj->getVx();
float vy1 = obj->getVy();
float vx2 = this->getVx();
float vy2 = this->getVy();
Collision::ResultCollision result = Collision::Instance()->sweptAABB(rect1, vx1, vy1, rect2, vx2, vy2);
//Chแป xรฉt hฦฐแปng va chแบกm tแปซ trรชn xuแปng
if (result.normaly == -1 || result.normaly == 0)
result.flag = false;
this->_start = (result.flag) ? true : _start;
if (result.flag)
{
Aladdin* aladdin = (Aladdin*)obj;
aladdin->JumpRotate();
result.intersectionPoint.x = obj->getX() + obj->getVx() * result.collisionTime;
result.intersectionPoint.y = obj->getY() + obj->getVy() *result.collisionTime;
}
return result;
}
void Stick::Render(Global::EDirection direct, Global::EState state, D3DXVECTOR3 position, D3DXVECTOR2 scale, D3DXVECTOR2 translation, float rotation, D3DXVECTOR2 rotationCenter)
{
Animation::Render(direct, state, position, scale, translation, rotation, rotationCenter);
}
void Stick::updateBody()
{
D3DXVECTOR2 position = D3DXVECTOR2(this->getCurrentLocation().x, this->getCurrentLocation().y + this->_height);
this->_rectBound.update(position.x, position.y, this->_width, this->_height);
}
void Stick::Refresh()
{
this->mListSprite[Global::JumpRun]->SetCurrentFrame(0);
}
void Stick::LoadResource()
{
std::vector<Rect*> listSourceRect = ResourceFile::Instance()->LoadXML(RESOURCE_RECT_ALADDIN, "stick");
listSourceRect[0]->setCenter(1, 18);
listSourceRect[1]->setCenter(1, 5);
listSourceRect[2]->setCenter(1, 18);
listSourceRect[3]->setCenter(2, 25);
listSourceRect[4]->setCenter(1, 18);
listSourceRect[5]->setCenter(1, 5);
listSourceRect[6]->setCenter(1, 18);
listSourceRect[7]->setCenter(2, 25);
listSourceRect[8]->setCenter(1, 18);
listSourceRect[9]->setCenter(1, 5);
listSourceRect[10]->setCenter(1, 18);
this->mListSprite[Global::JumpRun] = new SpriteManager(ResourceImage::Instance()->getStick(),
listSourceRect, false);
}
void Stick::UpdateRender(Global::EState currentState)
{
int size = this->mListSprite[currentState]->GetListRect().size();
int index = (this->GetCurrentFrame(currentState) + 1) % size;
this->SetCurrentFrame(currentState, index);
this->_start = (index == 0) ? false : this->_start;
}
| [
"15520564@gm.uit.edu.vn"
] | 15520564@gm.uit.edu.vn |
283c102d881ce28bdb670eff5c6ea2b1fcead6a4 | 37bebd58615bbcdaaa751285c86d59f82d4cb920 | /Chapter07/DiffuseExample/GamePlayScreen.cpp | df01288fea85cc4b66cb8e81b597b6c66ed89d74 | [
"MIT"
] | permissive | PacktPublishing/Mastering-Cpp-Game-Development | 80333bfa7f53912944f0df8b540508df0bdaba33 | 30b187250727e27edc1d9c8394eb6985eb84c873 | refs/heads/master | 2023-02-08T01:10:56.284355 | 2023-01-30T08:40:18 | 2023-01-30T08:40:18 | 117,197,589 | 79 | 37 | null | null | null | null | UTF-8 | C++ | false | false | 5,179 | cpp | /*
Copyright (c) 2016 Michael "Mickey" MacDonald.
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the Software
is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE
OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#include "GameplayScreen.h"
#include <iostream>
#include <SDL/SDL.h>
#include <BookEngine/IGame.h>
GameplayScreen::GameplayScreen()
{
}
GameplayScreen::~GameplayScreen()
{
}
void GameplayScreen::Build()
{
}
void GameplayScreen::Destroy()
{
}
void GameplayScreen::OnEntry()
{
std::cout << "OnEntry\n";
//glGenVertexArrays(1, &VertexArrayID);
//glBindVertexArray(VertexArrayID);
// Create and compile our GLSL program from the shaders
shaderManager.CompileShaders("Shaders/SimpleShader.vert", "Shaders/SimpleShader.frag");
shaderManager.AddAttribute("vertexPosition_modelspace");
shaderManager.AddAttribute("vertexColor");
shaderManager.AddAttribute("vertexNormal");
shaderManager.LinkShaders();
// Get a handle for our "MVP" a.k.a ModelViewProjection uniform
MatrixID = shaderManager.GetUniformLocation("ModelViewProjection");
//Init Camera
m_camera.Init();
//Init Model
m_model.Init("Meshes/Dwarf_2_Low.obj", "Textures/dwarf_2_1K_color.png");
m_game->GetInputManager().SetMouseCoords(float(1024 / 2), float(768 / 2));
}
void GameplayScreen::OnExit()
{
//glDeleteVertexArrays(1, &VertexArrayID);
}
void GameplayScreen::Update(float gameTime)
{
m_camera.Update();
CheckInput();
}
void GameplayScreen::Draw()
{
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glClearColor(1.0f, 0.0f, 0.0f, 1.0f);
// Cull triangles which normal is not towards the camera
glEnable(GL_CULL_FACE);
// Enable depth test
glEnable(GL_DEPTH_TEST);
// Accept fragment if it closer to the camera than the former one
glDepthFunc(GL_LESS);
//Use shader
shaderManager.Use();
GLint Kd = shaderManager.GetUniformLocation("Kd");
glUniform3f(Kd, 0.9f, 0.5f, 0.3f);
GLint Ld = shaderManager.GetUniformLocation("Ld");
glUniform3f(Ld, 1.0f, 1.0f, 1.0f);
glm::vec4 lightPos = m_camera.GetView() * glm::vec4(5.0f, 5.0f, 2.0f, 1.0f);
GLint lightPosUniform = shaderManager.GetUniformLocation("LightPosition");
glUniform4f(lightPosUniform, lightPos[0], lightPos[1], lightPos[2], lightPos[3]);
glm::mat4 modelView = m_camera.GetView() * glm::mat4(1.0f);
GLint modelViewUniform = shaderManager.GetUniformLocation("ModelViewMatrix");
glUniformMatrix4fv(modelViewUniform, 1, GL_FALSE, &modelView[0][0]);
glm::mat3 normalMatrix = glm::mat3(glm::vec3(modelView[0]), glm::vec3(modelView[1]), glm::vec3(modelView[2]));
GLint normalMatrixUniform = shaderManager.GetUniformLocation("NormalMatrix");
glUniformMatrix3fv(normalMatrixUniform, 1, GL_FALSE, &normalMatrix[0][0]);
// Send our transformation to the currently bound shader,
// in the "MVP" uniform
glUniformMatrix4fv(MatrixID, 1, GL_FALSE, &m_camera.GetMVPMatrix()[0][0]);
GLint textureUniform = shaderManager.GetUniformLocation("TextureSampler");
glUniform1i(textureUniform, 0);
//Draw Model
m_model.Draw();
//UnUse
shaderManager.UnUse();
}
int GameplayScreen::GetNextScreenIndex() const
{
return SCREENINDEX_NO_SCREEN;
}
int GameplayScreen::GetPreviousScreenIndex() const
{
return SCREENINDEX_NO_SCREEN;
}
void GameplayScreen::CheckInput()
{
SDL_Event event;
while (SDL_PollEvent(&event))
{
m_game->OnSDLEvent(event);
}
// Get mouse position
// Compute new orientation
m_camera.SetHorizontalAngle((float(1024 / 2) - m_game->GetInputManager().GetMouseCoords().x) / 100);// * m_deltaTime; //m_mouseSpeed;
m_camera.SetVerticalAngle((float(768 / 2) - m_game->GetInputManager().GetMouseCoords().y) / 100); //* m_deltaTime;
//m_game->GetInputManager().SetMouseCoords(float(1024 / 2), float(768 / 2));
// Move forward
if (m_game->GetInputManager().isKeyDown(SDLK_w)) {
m_camera.MoveCamera(m_camera.GetForward());//*m_deltaTime;
}
// Move backward
if (m_game->GetInputManager().isKeyDown(SDLK_s)) {
m_camera.MoveCamera(-m_camera.GetForward());//*m_deltaTime;
}
// Strafe right
if (m_game->GetInputManager().isKeyDown(SDLK_d)) {
m_camera.MoveCamera(m_camera.GetRight());// *m_deltaTime;
}
// Strafe left
if (m_game->GetInputManager().isKeyDown(SDLK_a)) {
m_camera.MoveCamera(-m_camera.GetRight());//*m_deltaTime;
}
}
| [
"mohdr@packtpub.com"
] | mohdr@packtpub.com |
876ebbae01ec31c5c9905451ea80439157ccf716 | 68e3cbcd32ef49a64267a92486ae7e0dc8f3916f | /cf 1345 A.cpp | 76bd9b21288f2a1b711a9b981235c251342828e3 | [] | no_license | star-platinum127/uva | d2db4e0078a502628257ac6b4b6ac7d6f4899e5e | fc660aad483909055f5397be267c4ce9c033c4ef | refs/heads/master | 2023-05-26T15:57:48.922938 | 2023-05-21T15:45:46 | 2023-05-21T15:45:46 | 240,208,573 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 537 | cpp | #include <bits/stdc++.h>
using namespace std;
typedef long long ll;
#define miku mywaifu
#define misaka mywaifu
#define pb push_back
#define S second
#define F first
#define mem(i,j) memset(i,j,sizeof(i))
#define pii pair<int,int>
#define MOD 1000000007
bool flag[200005];
int main() {
ios_base::sync_with_stdio();
cin.tie(0);
int t;
cin >> t;
while (t--) {
int n, m;
cin >> n >> m;
if (n == 1 || m == 1) cout << "YES" << endl;
else if (n == 2 && m == 2) cout << "YES" << endl;
else cout << "NO" << endl;
}
return 0;
}
| [
"noreply@github.com"
] | star-platinum127.noreply@github.com |
8a19632ed3e9128948763b46130405b62d87e4c5 | a257962bd37d65af2e93c65090f6ee30580d6e89 | /Game/mapdisp.cpp | 9dfc83109984fb1a56acb3106ffade7cbd73e355 | [] | no_license | pmprog/Overrun | 9c2d8612afc4b8fcc84fcb9688a035ea2d32cd74 | 505fb25c34209f3564771258d18f6a63aaae8837 | refs/heads/master | 2021-01-21T13:11:07.742350 | 2013-04-15T00:00:07 | 2013-04-15T00:00:07 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,801 | cpp |
#include "mapdisp.h"
#include "configure.h"
#include "Game/unit.h"
void MapDisp::Begin()
{
Cam = new Camera();
CameraDrag = false;
TileSize = min( CurrentConfiguration->ScreenWidth / 8, CurrentConfiguration->ScreenHeight / 8 );
ConfigFile* MapConfig = new ConfigFile( "Resource/NaturePath.txt" );
MapConfig->GetIntegerValue( "Width", &MapWidth );
MapConfig->GetIntegerValue( "Height", &MapHeight );
MapData = (uint8_t*)malloc( MapWidth * MapHeight * sizeof( uint8_t ) );
for( int y = 0; y < MapHeight; y++ )
{
for( int x = 0; x < MapWidth; x++ )
{
int t;
MapConfig->GetIntegerValue( "Map", (y * MapWidth) + x, &t );
MapData[(y * MapWidth) + x] = (uint8_t)t;
}
}
int pos;
float zm;
MapConfig->GetIntegerValue( "CameraPosX", &pos );
Cam->Position.X = pos * TileSize;
MapConfig->GetIntegerValue( "CameraPosY", &pos );
Cam->Position.Y = pos * TileSize;
MapConfig->GetFloatValue( "CameraZoom", &zm );
Cam->Zoom = zm;
delete MapConfig;
Cam->RotateOrigin.X = (TileSize * MapWidth) / 2;
Cam->RotateOrigin.Y = (TileSize * MapHeight) / 2;
GuiStage::Begin();
}
void MapDisp::Pause()
{
}
void MapDisp::Resume()
{
}
void MapDisp::Finish()
{
free( MapData );
GuiStage::Finish();
delete Cam;
}
void MapDisp::Event(ALLEGRO_EVENT *e)
{
Vector2 v;
if( e->type == ALLEGRO_EVENT_MOUSEEX_UP && CameraDrag )
CameraDrag = false;
GuiStage::Event( e );
if( e->any.timestamp == -1 )
return;
switch( e->type )
{
case ALLEGRO_EVENT_KEY_DOWN:
switch( e->keyboard.keycode )
{
case ALLEGRO_KEY_ESCAPE:
GameStack->Pop();
break;
case ALLEGRO_KEY_HOME:
Cam->MoveTo( &Cam->RotateOrigin, 4.0 );
break;
case ALLEGRO_KEY_END:
Cam->MoveTo( &Cam->RotateOrigin, 3.0 );
break;
case ALLEGRO_KEY_PGUP:
v.X = 0; v.Y = 0;
Cam->MoveTo( &v, 0.2 );
break;
case ALLEGRO_KEY_INSERT:
Cam->RotateTo( Cam->Rotation + 20, 3.0 );
break;
case ALLEGRO_KEY_DELETE:
Cam->RotateTo( Cam->Rotation - 20, 3.0 );
break;
}
break;
case ALLEGRO_EVENT_BUTTON_CLICK:
if( e->user.data1 == (intptr_t)testButton )
delete GameStack->Pop();
break;
case ALLEGRO_EVENT_MOUSEEX_DOWN:
if( e->user.data4 > 1 )
{
cursor->CancelBoxing();
CameraDrag = true;
} else {
Vector2 absPos;
Cam->CameraOffsetToAbsolute( ((Vector2*)e->user.data2), &absPos );
absPos.X++;
}
break;
case ALLEGRO_EVENT_MOUSEEX_UP:
if( CameraDrag )
CameraDrag = false;
break;
case ALLEGRO_EVENT_MOUSEEX_WHEEL:
Cam->ZoomTo( max( 0.4, min( 4.0, Cam->Zoom + ( ((double)e->user.data4 * 2.0) / 10 ) ) ), 0.02 );
break;
case ALLEGRO_EVENT_MOUSEEX_MOVE:
if( CameraDrag )
{
Vector2* d = (Vector2*)e->user.data3;
d->X = Cam->Position.X - (d->X / Cam->Zoom);
d->Y = Cam->Position.Y - (d->Y / Cam->Zoom);
Cam->MoveTo( d, 1000.0 );
}
break;
}
}
void MapDisp::Update()
{
Cam->Update();
GuiStage::Update();
cursor->Update();
}
void MapDisp::Render()
{
Vector2 pts[4];
al_clear_to_color( al_map_rgb( 0, 0, 0 ) );
for( int y = 0; y < MapHeight; y++ )
{
for( int x = 0; x < MapWidth; x++ )
{
pts[0].X = x * TileSize;
pts[1].X = x * TileSize;
pts[2].X = (x + 1) * TileSize;
pts[3].X = (x + 1) * TileSize;
pts[0].Y = y * TileSize;
pts[1].Y = (y + 1) * TileSize;
pts[2].Y = y * TileSize;
pts[3].Y = (y + 1) * TileSize;
Cam->AbsoluteToCameraOffset( &pts[0], &pts[0] );
Cam->AbsoluteToCameraOffset( &pts[1], &pts[1] );
Cam->AbsoluteToCameraOffset( &pts[2], &pts[2] );
Cam->AbsoluteToCameraOffset( &pts[3], &pts[3] );
DrawGround( x, y, (Vector2*)&pts );
}
}
GuiStage::Render();
cursor->Render();
}
void MapDisp::InitialiseGui()
{
cursor = new Mouse();
cursor->AllowBoxing = true;
testButton = new Button();
testButton->Position.X = 4;
testButton->Position.Y = 4;
testButton->Size.X = 200;
testButton->Size.Y = 32;
testButton->Text = "Quit";
testButton->FontSize = 16;
testButton->BorderWidth = 2;
Controls.push_back( testButton );
nextWave = new Panel();
nextWave->Position.X = CurrentConfiguration->ScreenWidth - 224;
nextWave->Position.Y = 4;
nextWave->Size.X = 220;
nextWave->Size.Y = 96;
nextWave->Background = al_map_rgba( 64, 128, 64, 128 );
nextWave->Border = al_map_rgb( 96, 192, 96 );
nextWave->BorderWidth = 2;
nextWave->Title = "Next Wave";
nextWave->HasTitle = true;
Controls.push_back( nextWave );
}
void MapDisp::UninitialiseGui()
{
Controls.remove( nextWave );
delete nextWave;
Controls.remove( testButton );
delete testButton;
delete cursor;
}
int MapDisp::GetMapElement( int X, int Y )
{
if( X < 0 || Y < 0 || X >= MapWidth || Y >= MapHeight )
return -1;
return MapData[(Y * MapWidth) + X];
}
void MapDisp::DrawGround( int X, int Y, Vector2 BasePoints[] )
{
float polyverts[8] = {
BasePoints[2].X, BasePoints[2].Y,
BasePoints[0].X, BasePoints[0].Y,
BasePoints[1].X, BasePoints[1].Y,
BasePoints[3].X, BasePoints[3].Y
};
switch( MapData[(Y * MapWidth) + X] )
{
case 0: // buildable
al_draw_filled_polygon( (float*)&polyverts, 4, al_map_rgb( 64, 128, 64 ) );
break;
case 1:
al_draw_filled_polygon( (float*)&polyverts, 4, al_map_rgb( 64, 64, 64 ) );
break;
case 2:
al_draw_filled_polygon( (float*)&polyverts, 4, al_map_rgb( 64, 64, 128 ) );
break;
}
al_draw_line( BasePoints[0].X, BasePoints[0].Y, BasePoints[1].X, BasePoints[1].Y, al_map_rgb(128,128,128), 1 );
al_draw_line( BasePoints[0].X, BasePoints[0].Y, BasePoints[2].X, BasePoints[2].Y, al_map_rgb(128,128,128), 1 );
al_draw_line( BasePoints[3].X, BasePoints[3].Y, BasePoints[1].X, BasePoints[1].Y, al_map_rgb(128,128,128), 1 );
al_draw_line( BasePoints[2].X, BasePoints[2].Y, BasePoints[3].X, BasePoints[3].Y, al_map_rgb(128,128,128), 1 );
}
| [
"devhead@pmprog.co.uk"
] | devhead@pmprog.co.uk |
a5860a694c095c5a1706b8b0b992ca273f7e2643 | 4cdc3c5a4c3323a1ca86c839086d0b102210ca00 | /IOCPServer/IOCP4Http/HTTP/HttpMessage.h | 4f007582a455e47b01e435e65cd550044e3555c2 | [
"MIT"
] | permissive | HanHanZai/workbean | 02ed2d77f215b422d4d23d58dc7915882e0ef537 | 9f22be684cee604f385b8aa1f6bf54e8603b92eb | refs/heads/master | 2023-07-06T11:39:49.920225 | 2021-08-06T00:56:26 | 2021-08-06T00:56:26 | 345,037,477 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 614 | h | #ifndef __HTTP_MESSAGE_H__
#define __HTTP_MESSAGE_H__
#include "../IOCP/BufferSlice.h"
#include <unordered_map>
struct HttpMessage
{
std::string m_version;
//std::string m_body;
std::unordered_map<std::string, std::string> m_headers;
std::string getHeaderField(const std::string& strKey);
void setHeader(std::string key, std::string value);
};
struct HttpRequest : public HttpMessage
{
enum RequestMethod
{
GET,
POST
};
size_t m_nHeaderLength;
std::string m_method;
std::string m_url;
Slice m_body;
};
struct HttpResponse : public HttpMessage
{
int m_status;
};
#endif // !__HTTP_MESSAGE_H__
| [
"824228502@qq.com"
] | 824228502@qq.com |
22e546d5b78d5ee22cbe57dfc876f6b0ae43b264 | 287dc1683f7e19a5239c2b8addbc8531809f9177 | /mooc50-bobo-DS/cppHoupengfei88/13-Red-Black-Tree/08-The-Performance-of-Red-Black-Tree/main.cpp | 55624d2dd05e32bd05fc3d13184a856e55db487c | [
"Apache-2.0"
] | permissive | yaominzh/CodeLrn2019 | ea192cf18981816c6adafe43d85e2462d4bc6e5d | adc727d92904c5c5d445a2621813dfa99474206d | refs/heads/master | 2023-01-06T14:11:45.281011 | 2020-10-28T07:16:32 | 2020-10-28T07:16:32 | 164,027,453 | 2 | 0 | Apache-2.0 | 2023-01-06T00:39:06 | 2019-01-03T22:02:24 | C++ | UTF-8 | C++ | false | false | 3,242 | cpp | #include <iostream>
#include "FileOperation.h"
#include "BST.h"
#include "RBTree.h"
#include "AVLTree.h"
template<typename T>
double testMap(T *map, string filename) {
clock_t startTime = clock();
srand(66);
vector<string> words;
if (FileOps::readFile(filename, words)) {
std::cout << "Total words: " << words.size() << std::endl;
for (string word : words) {
if (map->contains(word)) {
map->set(word, *(map->get(word)) + 1);
} else {
map->add(word, 1);
}
}
for (string word : words) {
map->contains(word);
}
std::cout << "Total different words: " << map->getSize() << std::endl;
std::cout << "Frequency of PRIDE: " << *(map->get("pride")) << std::endl;
std::cout << "Frequency of PREJUDICE: " << *(map->get("prejudice")) << std::endl;
}
clock_t endTime = clock();
return double(endTime - startTime) / CLOCKS_PER_SEC;
}
template<typename T>
double testData(T *map, vector<int> &dataes) {
clock_t startTime = clock();
for (int data : dataes) {
if (map->contains(data)) {
map->set(data, *(map->get(data)) + 1);
} else {
map->add(data, 1);
}
}
for (int data : dataes) {
map->contains(data);
}
clock_t endTime = clock();
return double(endTime - startTime) / CLOCKS_PER_SEC;
}
int main() {
std::cout << "pride-and-prejudice.txt" << std::endl;
string filename = ".././pride-and-prejudice.txt";
int n = 20000000;
vector<int> testDataes, testDataes1;
for (int i = 0; i < n; ++i) {
testDataes.push_back(rand() % INT64_MAX);
testDataes1.push_back(i);
}
BSTMap<string, int> *bstMap = new BSTMap<string, int>();
float time1 = testMap(bstMap, filename);
std::cout << "BSTMap time : " << time1 << " s " << std::endl;
RBTree<string, int> *rbTree = new RBTree<string, int>();
float time2 = testMap(rbTree, filename);
std::cout << "RBTree time : " << time2 << " s " << std::endl;
AVLTree<string, int> *avlTree = new AVLTree<string, int>();
float time3 = testMap(avlTree, filename);
std::cout << "AVLTree time : " << time3 << " s " << std::endl;
std::cout << "Test Dataes:" << std::endl;
BSTMap<int, int> *bstMap1 = new BSTMap<int, int>();
float time4 = testData(bstMap1, testDataes);
std::cout << "BSTMap time : " << time4 << " s " << std::endl;
RBTree<int, int> *rbTree1 = new RBTree<int, int>();
float time5 = testData(rbTree1, testDataes);
std::cout << "RBTree time : " << time5 << " s " << std::endl;
AVLTree<int, int> *avlTree1 = new AVLTree<int, int>();
float time6 = testData(avlTree1, testDataes);
std::cout << "AVLTree time : " << time6 << " s " << std::endl;
std::cout << "Test Dataes1" << std::endl;
RBTree<int, int> *rbTree2 = new RBTree<int, int>();
float time7 = testData(rbTree2, testDataes1);
std::cout << "RBTree time : " << time7 << " s " << std::endl;
AVLTree<int, int> *avlTree2 = new AVLTree<int, int>();
float time8 = testData(avlTree2, testDataes1);
std::cout << "AVLTree time : " << time8 << " s " << std::endl;
return 0;
}
| [
"mcuallen@gmail.com"
] | mcuallen@gmail.com |
742354b67d634ad78e124ca2a1c2155e810f87ba | 5856e2cd49a1571110bf9d4e408541c4d5a622fe | /blingfiretools/fa_dict2classifier/fa_dict2classifier.cpp | cec937167fd5abeac9156053ce02035eed6f477d | [
"LicenseRef-scancode-generic-cla",
"MIT"
] | permissive | tgarciai/BlingFire | c888828af472dd272f3e877b5f251a4d388e04af | afc8fdc7d2c789bb7a28c99cfb30f6a8e66f861c | refs/heads/master | 2022-04-18T16:57:40.148163 | 2020-04-17T21:17:27 | 2020-04-17T21:17:27 | 257,096,571 | 1 | 0 | MIT | 2020-04-19T20:33:48 | 2020-04-19T20:33:48 | null | UTF-8 | C++ | false | false | 6,194 | cpp | /**
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
#include "FAConfig.h"
#include "FAAllocator.h"
#include "FAUtils.h"
#include "FAAutIOTools.h"
#include "FAMapIOTools.h"
#include "FARSDfa_ro.h"
#include "FARSDfa_ar_judy.h"
#include "FAState2Ows_ar_uniq.h"
#include "FADict2Classifier.h"
#include "FAException.h"
#include <string>
#include <iostream>
#include <fstream>
const char * __PROG__ = "";
const char * pInFile = NULL;
const char * pOutFile = NULL;
const char * pInOw2FreqFile = NULL;
bool g_extend_ows_map = true;
bool g_extend_finals = false;
bool g_no_output = false;
int g_min_depth = 3;
int g_ows_merge_type = 0;
int g_ows_bound = 100;
FAAllocator g_alloc;
FAAutIOTools g_io (&g_alloc);
FAMapIOTools g_map_io (&g_alloc);
void usage () {
std::cout << "\n\
Usage: fa_dict2classifier [OPTION] [< input.txt] [> output.txt]\n\
\n\
This program builds a classifier from a dictionary.\n\
\n\
--in=<input-file> - input Moore Multi Dfa in textual form,\n\
if omited stdin is used\n\
\n\
--in-ow2f=<input-file> - reads Ow -> Freq array, if specified\n\
is not used by default\n\
\n\
--out=<output-file> - output Moore Multi Dfa,\n\
if omited stdout is used\n\
\n\
--min-depth=N - sets up minimum prefix length starting from which\n\
each state in automaton will have a reaction, 3 is used by default\n\
\n\
--keep-state2ows - won't make any extension of State -> Ows map,\n\
--min-depth=N parameter will be ignored\n\
\n\
--ows-merge=<type> - specifies how Ows are merged, if extending state2ows\n\
or - union of Ows, is used by default\n\
and - intersection of Ows\n\
\n\
--ows-bound=N - sets up % of Ows to be used for State2Ow extension, from\n\
more to less frequent; all are taken by default; used with --in-ow2f only\n\
\n\
--extend-finals - states with added output weights due to extension will\n\
be marked as final, won't be by default\n\
\n\
--no-output - makes no output\n\
\n\
";
}
void process_args (int& argc, char**& argv)
{
for (; argc--; ++argv) {
if (!strcmp ("--help", *argv)) {
usage ();
exit (0);
}
if (0 == strncmp ("--in=", *argv, 5)) {
pInFile = &((*argv) [5]);
continue;
}
if (0 == strncmp ("--in-ow2f=", *argv, 10)) {
pInOw2FreqFile = &((*argv) [10]);
continue;
}
if (0 == strncmp ("--out=", *argv, 6)) {
pOutFile = &((*argv) [6]);
continue;
}
if (0 == strncmp ("--min-depth=", *argv, 12)) {
g_min_depth = atoi (&((*argv) [12]));
continue;
}
if (0 == strncmp ("--ows-bound=", *argv, 12)) {
g_ows_bound = atoi (&((*argv) [12]));
continue;
}
if (0 == strcmp ("--no-output", *argv)) {
g_no_output = true;
continue;
}
if (0 == strcmp ("--keep-state2ows", *argv)) {
g_extend_ows_map = false;
continue;
}
if (0 == strcmp ("--ows-merge=or", *argv)) {
g_ows_merge_type = 0;
continue;
}
if (0 == strcmp ("--ows-merge=and", *argv)) {
g_ows_merge_type = 1;
continue;
}
if (0 == strcmp ("--extend-finals", *argv)) {
g_extend_finals = true;
continue;
}
}
}
int __cdecl main (int argc, char ** argv)
{
__PROG__ = argv [0];
--argc, ++argv;
::FAIOSetup ();
// parse a command line
process_args (argc, argv);
try {
// select in/out streams
std::istream * pIs = &std::cin;
std::ifstream ifs;
std::ostream * pOs = &std::cout;
std::ofstream ofs;
if (NULL != pInFile) {
ifs.open (pInFile, std::ios::in);
FAAssertStream (&ifs, pInFile);
pIs = &ifs;
}
if (NULL != pOutFile) {
ofs.open (pOutFile, std::ios::out);
pOs = &ofs;
}
DebugLogAssert (pIs);
DebugLogAssert (pOs);
FARSDfa_ro input_dfa (&g_alloc);
FAState2Ows_ar_uniq input_ows (&g_alloc);
FARSDfa_ar_judy output_dfa (&g_alloc);
FAState2Ows_ar_uniq output_ows (&g_alloc);
FADict2Classifier build_classifier (&g_alloc);
/// read input Dfa
g_io.Read (*pIs, &input_dfa, &input_ows);
/// read Ow -> Freq array, if any
if (NULL != pInOw2FreqFile) {
std::ifstream ifs_ow2f (pInOw2FreqFile, std::ios::in);
FAAssertStream (&ifs_ow2f, pInOw2FreqFile);
const int * pOw2Freq = NULL;
int Count = 0;
g_map_io.Read (ifs_ow2f, &pOw2Freq, &Count);
FAAssert (pOw2Freq && 0 < Count, FAMsg::IOError);
build_classifier.SetOw2Freq (pOw2Freq, Count);
build_classifier.SetOwsBound (g_ows_bound);
}
build_classifier.SetMinDepth (g_min_depth);
build_classifier.SetExtendState2Ows (g_extend_ows_map);
build_classifier.SetOwsMergeType (g_ows_merge_type);
build_classifier.SetExtendFinals (g_extend_finals);
build_classifier.SetInMooreDfa (&input_dfa, &input_ows);
build_classifier.SetOutMooreDfa (&output_dfa, &output_ows);
build_classifier.Process ();
if (false == g_no_output) {
g_io.Print (*pOs, &output_dfa, &output_ows);
}
} catch (const FAException & e) {
const char * const pErrMsg = e.GetErrMsg ();
const char * const pFile = e.GetSourceName ();
const int Line = e.GetSourceLine ();
std::cerr << "ERROR: " << pErrMsg << " in " << pFile \
<< " at line " << Line << " in program " << __PROG__ << '\n';
return 2;
} catch (...) {
std::cerr << "ERROR: Unknown error in program " << __PROG__ << '\n';
return 1;
}
return 0;
}
| [
"jiamguo@microsoft.com"
] | jiamguo@microsoft.com |
fa363b01e63a295131d58febe83d5c645f36e32f | 863ecfa18260f75e97dcaee2ed7dab8d5eba73d7 | /A7-3-810197648/handlers.cpp | 5436d6968db253fbc0c95dfc8fec9a4529274346 | [] | no_license | atiarmn/utflix | 7acb2663f4835e34c011a5f3472d5eaf6fd18e33 | 4cc379107343fcd1687589177d948062a6d4d45d | refs/heads/master | 2020-05-24T17:17:58.519869 | 2019-06-05T17:14:44 | 2019-06-05T17:14:44 | 187,380,673 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 28,139 | cpp | #include "handlers.hpp"
using namespace std;
Response *ErrorHandler::callback(Request *req){
Database* database = database->get_instance();
Response *res=new Response();
res->setHeader("Content-Type","text/html");
string error_msg = req->getQueryParam("error_msg");
string new_url = req->getQueryParam("url");
string body;
body += "<!DOCTYPE html>";
body += "<html>";
body +="<head><style> body {background-image: url(\"static/projection-05.jpg\");";
body+="background-repeat: no-repeat;background-attachment: fixed;background-position: center;background-size: cover;}";
body+="a{color:darkred;margin-left: 550px;text-align: center;}a:link {text-decoration: none;}";
body+="a:visited {text-decoration: none;}a:hover {text-decoration: underline;}a:active {text-decoration: underline;}";
body+="</style><head>";
body += "<body>";
body += "<h1 style=\"color: darkred;text-align: center;\">";
body += error_msg;
body += "</h1>";
body += "<a href=\"";
if(new_url == "homepage"){
if(database->get_user_by_id(stoi(req->getSessionId()))->get_type())
new_url+="?type=publisher";
else
new_url+="?type=user";
}
body += new_url;
body += "\">";
if(new_url=="login")
body+="LOGIN";
else if(new_url=="homepage?type=user"||new_url=="homepage?type=publisher")
body+="HOMEPAGE";
else
body += "BACK";
body += "</a>";
body += "</body>";
body += "</html>";
res->setBody(body);
return res;
}
Response *LogoutHandler::callback(Request *req){
Response *res = new Response();
Database* database = database->get_instance();
if(database->is_loggedin(stoi(req->getSessionId())))
database->logout(stoi(req->getSessionId()));
else{
res = Response::redirect("/error?error_msg=you+are+not+login&url=login");
return res;
}
res = Response::redirect("/login");
informations.clear();
res->setSessionId("");
return res;
}
Response *SignupHandler::callback(Request *req) {
string redirect;
Response *res = new Response();
Database* database = database->get_instance();
informations["username"] = req->getBodyParam("username");
informations["password"] = req->getBodyParam("password");
informations["age"] = req->getBodyParam("age");
informations["email"] = req->getBodyParam("email");
informations["publisher"] = req->getBodyParam("publisher");
string repeat_password = req->getBodyParam("repeat_password");
if(repeat_password!=informations["password"]){
redirect="/error?error_msg=password+and+repeated+password+are+different&url=signup";
res = Response::redirect(redirect);
return res;
}
if(req->getSessionId()!=""){
redirect="/error?error_msg=you+didnt+logout&url=homepage";
res = Response::redirect(redirect);
return res;
}
Signup* signup = new Signup();
redirect=signup->post(informations);
int id;
id=database->find_last_user();
res = Response::redirect(redirect);
database->login(id);
res->setSessionId(to_string(id));
return res;
}
Response *LoginHandler::callback(Request *req) {
string redirect;
Database* database = database->get_instance();
Response *res = new Response();
informations["username"] = req->getBodyParam("username");
informations["password"] = req->getBodyParam("password");
if(req->getSessionId()!=""){
redirect="/error?error_msg=you+didnt+logout&url=homepage";
res = Response::redirect(redirect);
return res;
}
Login* login = new Login();
redirect=login->post(informations);
int id=-1;
if(database->get_user(informations["username"])!=NULL)
id=database->get_user(informations["username"])->get_id();
res = Response::redirect(redirect);
if(id!=-1){
database->login(id);
res->setSessionId(to_string(id));
}
return res;
}
Response *HomepageHandler::callback(Request *req){
Response *res = new Response();
Database* database = database->get_instance();
if(!database->is_loggedin(stoi(req->getSessionId()))){
res = Response::redirect("/error?error_msg=you+are+not+login&url=login");
return res;
}
string type = req->getQueryParam("type");
if(type=="publisher")
res = Response::redirect("/publisherHomepage");
if(type=="user")
res = Response::redirect("/userHomepage");
return res;
}
Response *PostFilmHandler::callback(Request *req){
Response *res = new Response();
Database* database = database->get_instance();
if(!database->is_loggedin(stoi(req->getSessionId()))){
res = Response::redirect("/error?error_msg=you+are+not+login&url=login");
return res;
}
informations["name"]=req->getBodyParam("name");
informations["year"]=req->getBodyParam("year");
informations["length"]=req->getBodyParam("length");
informations["director"]=req->getBodyParam("director");
informations["summary"]=req->getBodyParam("summary");
informations["price"]=req->getBodyParam("price");
Film* film = new Film(informations,database->get_user_by_id(stoi(req->getSessionId())));
try{
film->post(database->get_user_by_id(stoi(req->getSessionId())));
database->get_user_by_id(stoi(req->getSessionId()))->add_film(film->get_id());
}catch(exception& ex){
res=Response::redirect("/error?error_msg=you+cant+post+a+film&url=homepage");
return res;
}
res=Response::redirect("/publisherHomepage");
return res;
}
Response *PublishedHandler::callback(Request *req){
Database* database = database->get_instance();
Response *res = new Response();
if(!database->is_loggedin(stoi(req->getSessionId()))){
res = Response::redirect("/error?error_msg=you+are+not+login&url=login");
return res;
}
res->setHeader("Content-Type","text/html");
vector<Film*> published_films;
string body;
informations["director"]=req->getQueryParam("director");
Film* film=new Film();
try{
published_films=film->get_published(database->get_user_by_id(stoi(req->getSessionId())),informations);
}catch(exception& ex){
res=Response::redirect("/error?error_msg=you+doont+have+published+films&url=homepage");
return res;
}
body+="<!DOCTYPE html>";
body+="<html>";
body +="<head><style> body {background-image: url(\"static/projection-05.jpg\");";
body+="background-repeat: no-repeat;background-attachment: fixed;background-position: center;background-size: cover;}";
body+="div {background-color:black; padding: 1%; max-width: 300px; border-radius: 3px; margin-left: 500px;}";
body+="h2{color:darkred;text-align: center;}";
body+="p{color:darkred;}";
body+=".button {border: none;color: white;padding: 16px 32px;text-decoration: none;margin: 4px 2px;cursor: pointer;display: inline-block;}";
body+=".button span {cursor: pointer;display: inline-block;position: relative;transition: 0.5s;}";
body+=".button span:after {content: '\\00bb';position: absolute;opacity: 0;top: 0;right: -20px;transition: 0.5s;}";
body+=".button:hover span {padding-right: 25px;}.button:hover span:after {opacity: 1;right: 0;}";
body+="table {border-collapse: collapse;width: 100%;background-color: darkred;}";
body+="th, td {padding: 8px;text-align: left;border-bottom: 1px solid #ddd;}tr:hover {background-color:rgb(177, 9, 0);}";
body+="</style></head>";
body+="<body>";
body+="<h1>Your Films!</h1>";
body+="<div>";
body+="<form action=\"/search\" method=\"post\">";
body+="<h2>Search</h2>";
body+="<p>director:</p><input type=\"text\" name=\"director\" placeholder=\"Director\"/><br>";
body+="<button type=\"submit\" style=\"background-color: darkred;\" class=\"button\"><span>Search</span></button>";
body+="</form>";
body+="</div>";
body+="<table>";
body+="<tr>";
body+="<th>Name</th>";
body+="<th>Length</th>";
body+="<th>Price</th>";
body+="<th>Year</th>";
body+="<th>Rate</th>";
body+="<th>Director</th>";
body+="<th>Delete</th>";
body+="</tr>";
for(int i=0;i<published_films.size();i++){
body+="<tr>";
body+="<th>";
body+=published_films[i]->get_name();
body+="</th>";
body+="<th>";
body+=published_films[i]->get_length();
body+="</th>";
body+="<th>";
body+=to_string(published_films[i]->get_price());
body+="</th>";
body+="<th>";
body+=published_films[i]->get_year();
body+="</th>";
body+="<th>";
stringstream stream;
stream << fixed << setprecision(2) << published_films[i]->get_rate();
body+=stream.str();
body+="</th>";
body+="<th>";
body+=published_films[i]->get_director();
body+="</th>";
body+="<form action=\"/delete\" method=\"post\">";
body+="<th><button name=\"film_id\" style=\"background-color: black;\" type=\"submit\" class=\"button\" value=\"";
body+=to_string(published_films[i]->get_id());
body+="\"><span>Delete</span></button></th>";
body+="</form>";
body+="</tr>";
}
body+="</table></div></body></html>";
res->setBody(body);
return res;
}
Response *DeleteFilmHandler::callback(Request *req){
Database* database = database->get_instance();
Response *res=new Response();
if(!database->is_loggedin(stoi(req->getSessionId()))){
res = Response::redirect("/error?error_msg=you+are+not+login&url=login");
return res;
}
informations["film_id"]=req->getBodyParam("film_id");
Film* film = new Film();
film->delete_film(informations);
res = Response::redirect("/publishedFilms");
return res;
}
Response *SearchFilmHandler::callback(Request *req){
string director = req->getBodyParam("director");
Response *res = new Response();
string redirect;
redirect += "/publishedFilms?director=";
redirect += director;
res=Response::redirect(redirect);
return res;
}
Response *ProfileHandler::callback(Request *req){
Response *res = new Response();
Database* database = database->get_instance();
if(!database->is_loggedin(stoi(req->getSessionId()))){
res = Response::redirect("/error?error_msg=you+are+not+login&url=login");
return res;
}
vector<Film*> purchased_films;
string body;
informations["director"]=req->getQueryParam("director");
Film* film=new Film();
purchased_films=film->get_purchased(database->get_user_by_id(stoi(req->getSessionId())));
res->setHeader("Content-Type","text/html");
body+="<!DOCTYPE html>";
body+="<html>";
body +="<head><style> body {background-image: url(\"static/projection-05.jpg\");";
body+="background-repeat: no-repeat;background-attachment: fixed;background-position: center;background-size: cover;}";
body+="div {background-color:black; padding: 1%; max-width: 300px; border-radius: 1px; margin-left: 500px;}";
body+="h1{color:darkred;text-align: center;}";
body+="p{color:darkred;}";
body+=".button {border: none;color: white;padding: 16px 32px;text-decoration: none;margin: 4px 2px;cursor: pointer;display: inline-block;}";
body+=".button span {cursor: pointer;display: inline-block;position: relative;transition: 0.5s;}";
body+=".button span:after {content: '\\00bb';position: absolute;opacity: 0;top: 0;right: -20px;transition: 0.5s;}";
body+=".button:hover span {padding-right: 25px;}.button:hover span:after {opacity: 1;right: 0;}";
body+="table {border-collapse: collapse;width: 100%;background-color: darkred;}";
body+="th, td {padding: 8px;text-align: left;border-bottom: 1px solid #ddd;}tr:hover {background-color:rgb(177, 9, 0);}";
body+="</style></head>";
body+="<body>";
body+="<div>";
body+="<h1>Your Films!</h1>";
body+="</div>";
body+="<table>";
body+="<tr>";
body+="<th>Name</th>";
body+="<th>Length</th>";
body+="<th>Price</th>";
body+="<th>Year</th>";
body+="<th>Rate</th>";
body+="<th>Director</th>";
body+="<th>Details</th>";
body+="</tr>";
for(int i=0;i<purchased_films.size();i++){
body+="<tr>";
body+="<th>";
body+=purchased_films[i]->get_name();
body+="</th>";
body+="<th>";
body+=purchased_films[i]->get_length();
body+="</th>";
body+="<th>";
body+=to_string(purchased_films[i]->get_price());
body+="</th>";
body+="<th>";
body+=purchased_films[i]->get_year();
body+="</th>";
body+="<th>";
stringstream stream;
stream << fixed << setprecision(2) << purchased_films[i]->get_rate();
body+=stream.str();
body+="</th>";
body+="<th>";
body+=purchased_films[i]->get_director();
body+="</th>";
body+="<form action=\"/showDetails\" method=\"get\">";
body+="<th><button name=\"film_id\" class=\"button\" style=\"background-color:black\" type=\"submit\" value=\"";
body+=to_string(purchased_films[i]->get_id());
body+="\"><span>ShowDetails</span></button></th></form>";
body+="</tr>";
}
body+="</table>";
body+="<div>";
body+="<form action=\"/addMoney\" method=\"post\">";
body+="<input type=\"number\" name=\"amount\" min=\"1\" placeholder=\"Amount\"/><br>";
body+="<button type=\"submit\" class=\"button\" style=\"background-color:darkred\" ><span>add</span></button>";
body+="</form></div></body></html>";
res->setBody(body);
return res;
}
Response *RateHandler::callback(Request *req){
Database* database = database->get_instance();
Response *res = new Response();
Rate* rate = new Rate();
informations["score"]=req->getBodyParam("score");
informations["film_id"]=req->getBodyParam("film_id");
try{
rate->post(database->get_user_by_id(stoi(req->getSessionId())),informations);
}catch(exception& ex){
res=Response::redirect("/error?error_msg=film+is+deleted&url=profile");
return res;
}
string body;
res->setHeader("Content-Type","text/html");
body+="<!DOCTYPE html>";
body+="<html>";
body+="<head><style> body {background-image: url(\"static/projection-05.jpg\");";
body+="background-repeat: no-repeat;background-attachment: fixed;background-position: center;background-size: cover;}";
body+="div {background-color:black; padding: 1%; max-width: 300px; border-radius: 1px; margin-left: 500px;}";
body+=".button {background-color:darkred;border: none;color: white;padding: 16px 32px;text-decoration: none;margin: 4px 2px;cursor: pointer;display: inline-block;}";
body+=".button span {cursor: pointer;display: inline-block;position: relative;transition: 0.5s;}";
body+=".button span:after {content: '\\00bb';position: absolute;opacity: 0;top: 0;right: -20px;transition: 0.5s;}";
body+="</style><head>";
body+="<body>";
body+="<div>";
body+="<h1 style=\"color: darkred;text-align: center;\">thanks</h1>";
body+="<form action=\"/showDetails\" method=\"get\">";
body+="<th><button name=\"film_id\" class=\"button\" type=\"submit\" value=\"";
body+=informations["film_id"];
body+="\"><span>OK</span></button></th></form>";
body+="</div></body></html>";
res->setBody(body);
return res;
}
Response *AddMoneyHandler::callback(Request *req){
Database* database = database->get_instance();
informations["amount"] = req->getBodyParam("amount");
Response *res = new Response();
Money* money = new Money();
money->post_user(database->get_user_by_id(stoi(req->getSessionId())),informations);
string body;
res->setHeader("Content-Type","text/html");
body+="<!DOCTYPE html>";
body+="<html>";
body+="<body>";
body+="<head><style> body {background-image: url(\"static/projection-05.jpg\");";
body+="background-repeat: no-repeat;background-attachment: fixed;background-position: center;background-size: cover;}";
body+="div {background-color:black; padding: 1%; max-width: 300px; border-radius: 1px; margin-left: 500px;}";
body+=".button {background-color:darkred; border: none;color: white;padding: 16px 32px;text-decoration: none;margin: 4px 2px;cursor: pointer;display: inline-block;}";
body+=".button span {cursor: pointer;display: inline-block;position: relative;transition: 0.5s;}";
body+=".button span:after {content: '\\00bb';position: absolute;opacity: 0;top: 0;right: -20px;transition: 0.5s;}";
body+="</style><head>";
body+="<div>";
body+="<h1 style=\"color: darkred;text-align: center;\">you have";
body+=to_string(database->get_user_by_id(stoi(req->getSessionId()))->get_money());
body+="</h1>";
body+="<form action=\"/profile\" method=\"get\">";
body+="<button type=\"submit\" class=\"button\"><span>OK</span></button>";
body+="</form>";
body+="</div></body></html>";
res->setBody(body);
return res;
}
Response *CanBuyFilmHandler::callback(Request *req){
Response *res = new Response();
Database* database = database->get_instance();
if(!database->is_loggedin(stoi(req->getSessionId()))){
res = Response::redirect("/error?error_msg=you+are+not+login&url=login");
return res;
}
vector<Film*> films;
string body;
Film* film=new Film();
films=film->get_films(database->get_user_by_id(stoi(req->getSessionId())));
res->setHeader("Content-Type","text/html");
body+="<!DOCTYPE html>";
body+="<html>";
body +="<head><style> body {background-image: url(\"static/projection-05.jpg\");";
body+="background-repeat: no-repeat;background-attachment: fixed;background-position: center;background-size: cover;}";
body+="div {background-color:black; padding: 1%; max-width: 300px; border-radius: 1px; margin-left: 500px;}";
body+="h1{color:darkred;text-align: center;}";
body+="p{color:darkred;}";
body+=".button {border: none;color: white;padding: 16px 32px;text-decoration: none;margin: 4px 2px;cursor: pointer;display: inline-block;}";
body+=".button span {cursor: pointer;display: inline-block;position: relative;transition: 0.5s;}";
body+=".button span:after {content: '\\00bb';position: absolute;opacity: 0;top: 0;right: -20px;transition: 0.5s;}";
body+=".button:hover span {padding-right: 25px;}.button:hover span:after {opacity: 1;right: 0;}";
body+="table {border-collapse: collapse;width: 100%;background-color: darkred;}";
body+="th, td {padding: 8px;text-align: left;border-bottom: 1px solid #ddd;}tr:hover {background-color:rgb(177, 9, 0);}";
body+="</style></head>";
body+="<body>";
body+="<div>";
body+="<h1>Films You Can Buy!</h1></div>";
body+="<table>";
body+="<tr>";
body+="<th>Name</th>";
body+="<th>Length</th>";
body+="<th>Price</th>";
body+="<th>Year</th>";
body+="<th>Rate</th>";
body+="<th>Director</th>";
body+="<th>Details</th>";
body+="</tr>";
for(int i=0;i<films.size();i++){
body+="<tr>";
body+="<th>";
body+=films[i]->get_name();
body+="</th>";
body+="<th>";
body+=films[i]->get_length();
body+="</th>";
body+="<th>";
body+=to_string(films[i]->get_price());
body+="</th>";
body+="<th>";
body+=films[i]->get_year();
body+="</th>";
body+="<th>";
stringstream stream;
stream << fixed << setprecision(2) << films[i]->get_rate();
body+=stream.str();
body+="</th>";
body+="<th>";
body+=films[i]->get_director();
body+="</th>";
body+="<form action=\"/showDetails\" method=\"get\">";
body+="<th><button name=\"film_id\" class=\"button\" style=\"background-color:black\" type=\"submit\" value=\"";
body+=to_string(films[i]->get_id());
body+="\"><span>ShowDetails</span></button></th></form>";
body+="</tr>";
}
body+="</table></body></html>";
res->setBody(body);
return res;
}
Response *DetailsHandler::callback(Request *req){
Database* database = database->get_instance();
Response *res=new Response();
if(!database->is_loggedin(stoi(req->getSessionId()))){
res = Response::redirect("/error?error_msg=you+are+not+login&url=login");
return res;
}
string film_id = req->getQueryParam("film_id");
int count=1;
Film *film = database->get_film(stoi(film_id));
vector<Film*> recommend_films;
FilmService *service = new FilmService();
string body;
res->setHeader("Content-Type","text/html");
body+="<!DOCTYPE html>";
body+="<html>";
body +="<head><style> body {background-image: url(\"static/projection-05.jpg\");";
body+="background-repeat: no-repeat;background-attachment: fixed;background-position: center;background-size: cover;}";
body+="div {background-color:black; padding: 1%; max-width: 300px; border-radius: 1px; margin-left: 500px;}";
body+="h1{color:darkred;text-align: center;}";
body+="p{color:darkred;}";
body+=".button {border: none;color: white;padding: 16px 32px;text-decoration: none;margin: 4px 2px;cursor: pointer;display: inline-block;}";
body+=".button span {cursor: pointer;display: inline-block;position: relative;transition: 0.5s;}";
body+=".button span:after {content: '\\00bb';position: absolute;opacity: 0;top: 0;right: -20px;transition: 0.5s;}";
body+=".button:hover span {padding-right: 25px;}.button:hover span:after {opacity: 1;right: 0;}";
body+="table {border-collapse: collapse;width: 100%;background-color: darkred;}";
body+="th, td {padding: 8px;text-align: left;border-bottom: 1px solid #ddd;}tr:hover {background-color:rgb(177, 9, 0);}";
body+="</style></head>";
body+="<body>";
body+="<div>";
body+="<h1>Details of Film:</h1></div>";
body+="<table>";
body+="<tr>";
body+="<th>Name</th>";
body+="<th>Length</th>";
body+="<th>Price</th>";
body+="<th>Year</th>";
body+="<th>Summary</th>";
body+="<th>Director</th>";
body+="<th>Rate</th>";
if(!database->get_user_by_id(stoi(req->getSessionId()))->film_bought(film->get_id()))
body+="<th>Buy</th>";
else{
body+="<th>Score the film</th>";
body+="<th>Add comment</th>";
}
body+="</tr>";
body+="<tr>";
body+="<th>";
body+=film->get_name();
body+="</th>";
body+="<th>";
body+=film->get_length();
body+="</th>";
body+="<th>";
body+=to_string(film->get_price());
body+="</th>";
body+="<th>";
body+=film->get_year();
body+="</th>";
body+="<th>";
body+=film->get_summary();
body+="</th>";
body+="<th>";
body+=film->get_director();
body+="</th>";
body+="<th>";
stringstream stream;
stream << fixed << setprecision(2) << film->get_rate();
body+=stream.str();
body+="</th>";
if(!database->get_user_by_id(stoi(req->getSessionId()))->film_bought(film->get_id())){
body+="<form action=\"/buy\" method=\"post\">";
body+="<th><button name=\"film_id\" class=\"button\" style=\"background-color:black\" type=\"submit\" value=\"";
body+=to_string(film->get_id());
body+="\"><span>Buy</span></button></th>";
body+="</form>";
}
else{
body+="<form action=\"/rate\" method=\"post\">";
body+="<th><input type=\"number\" name=\"score\" min=\"0\" max=\"10\" placeholder=\"score\"/>";
body+="<button name=\"film_id\" class=\"button\" style=\"background-color:black\" type=\"submit\" value=\"";
body+=to_string(film->get_id());
body+="\"><span>Score</span></button></th></form>";
body+="<form action=\"/comment\" method=\"post\">";
body+="<th><input type=\"text\" name=\"comment\" placeholder=\"Your Comment\" required>";
body+="<button name=\"film_id\" type=\"submit\" class=\"button\" style=\"background-color:black\" value=\"";
body+=to_string(film->get_id());
body+="\"><span>Post</span></button></th></form>";
}
body+="</tr>";
body+="</table>";
body+="<div><h1>Comments!</h1></div>";
body+="<table><tr>";
body+="<th>comment id</th>";
body+="<th>content</th></tr>";
vector<Comment*> comments=film->get_comments();
for(int i=0;i<comments.size();i++){
body+="<tr><th>";
body+=to_string(comments[i]->get_id());
body+="</th><th>";
body+=comments[i]->get_content();
body+="</th></tr>";
}
body+="</table><div><h1>Recommended Films!</h1></div><table>";
body+="<tr>";
body+="<th>Name</th>";
body+="<th>Length</th>";
body+="<th>Director</th>";
body+="<th>Details</th>";
body+="</tr>";
for(int i=0;i<(service->recommend(film->get_id())).size();i++)
recommend_films.push_back(service->recommend(film->get_id())[i]);
for(int i=0;i<recommend_films.size();i++){
if(count>4)
break;
if(recommend_films[i]->get_id()==film->get_id() ||
recommend_films[i]->deleted() ||
database->get_user_by_id(stoi(req->getSessionId()))->film_bought(recommend_films[i]->get_id())){
continue;
}
body+="<tr><th>";
body+=recommend_films[i]->get_name();
body+="</th><th>";
body+=recommend_films[i]->get_length();
body+="</th><th>";
body+=recommend_films[i]->get_director();
body+="</th>";
body+="<form action=\"/showDetails\" method=\"get\">";
body+="<th><button name=\"film_id\" class=\"button\" style=\"background-color:black\" type=\"submit\" value=\"";
body+=to_string(recommend_films[i]->get_id());
body+="\"><span>ShowDetails</span></button></th></form>";
body+="</tr>";
count++;
}
body+="</body></html>";
res->setBody(body);
return res;
}
Response *CommentHandler::callback(Request *req){
Response *res = new Response();
Database* database = database->get_instance();
informations["content"]=req->getBodyParam("comment");
informations["film_id"]=req->getBodyParam("film_id");
Comment* comment = new Comment(informations["content"],stoi(req->getSessionId()));
try{
comment->post(database->get_user_by_id(stoi(req->getSessionId())),informations);
}catch(exception& ex){
res=Response::redirect("/error?error_msg=film+is+deleted&url=profile");
return res;
}
string body;
res->setHeader("Content-Type","text/html");
body+="<!DOCTYPE html>";
body+="<html>";
body+="<head><style> body {background-image: url(\"static/projection-05.jpg\");";
body+="background-repeat: no-repeat;background-attachment: fixed;background-position: center;background-size: cover;}";
body+="div {background-color:black; padding: 1%; max-width: 300px; border-radius: 1px; margin-left: 500px;}";
body+=".button {background-color:darkred; border:none;color: white;padding: 16px 32px;text-decoration: none;margin: 4px 2px;cursor: pointer;display: inline-block;}";
body+=".button span {cursor: pointer;display: inline-block;position: relative;transition: 0.5s;}";
body+=".button span:after {content: '\\00bb';position: absolute;opacity: 0;top: 0;right: -20px;transition: 0.5s;}";
body+="</style><head>";
body+="<body>";
body+="<div>";
body+="<h1 style=\"color: darkred;text-align: center;\">thanks</h1>";
body+="<form action=\"/showDetails\" method=\"get\">";
body+="<th><button name=\"film_id\" class=\"button\" type=\"submit\" value=\"";
body+=informations["film_id"];
body+="\"><span>OK</span></button></th></form>";
body+="</form>";
body+="</div></body></html>";
res->setBody(body);
return res;
}
Response *BuyFilmHandler::callback(Request *req){
Database* database = database->get_instance();
Response *res=new Response();
if(!database->is_loggedin(stoi(req->getSessionId()))){
res = Response::redirect("/error?error_msg=you+are+not+login&url=login");
return res;
}
informations["film_id"]=req->getBodyParam("film_id");
Buy *buy = new Buy();
try{
buy->post(database->get_user_by_id(stoi(req->getSessionId())),informations);
}catch(exception &ex){
res=Response::redirect("/error?error_msg=you+dont+have+enough+money&url=details");
return res;
}
string body;
res->setHeader("Content-Type","text/html");
body+="<!DOCTYPE html>";
body+="<html>";
body+="<head><style> body {background-image: url(\"static/projection-05.jpg\");";
body+="background-repeat: no-repeat;background-attachment: fixed;background-position: center;background-size: cover;}";
body+="div {background-color:black; padding: 1%; max-width: 300px; border-radius: 1px; margin-left: 500px;}";
body+=".button {background-color:darkred; border:none;color: white;padding: 16px 32px;text-decoration: none;margin: 4px 2px;cursor: pointer;display: inline-block;}";
body+=".button span {cursor: pointer;display: inline-block;position: relative;transition: 0.5s;}";
body+=".button span:after {content: '\\00bb';position: absolute;opacity: 0;top: 0;right: -20px;transition: 0.5s;}";
body+="</style><head>";
body+="<body>";
body+="<div>";
body+="<h1 style=\"color: darkred;text-align: center;\">thanks</h1>";
body+="<form action=\"/showDetails\" method=\"get\">";
body+="<th><button name=\"film_id\" class=\"button\" type=\"submit\" value=\"";
body+=informations["film_id"];
body+="\"><span>OK</span></button></th></form>";
body+="</form>";
body+="</div></body></html>";
res->setBody(body);
return res;
} | [
"atieharmin08@gmail.com"
] | atieharmin08@gmail.com |
bc85d07c8bb4927a7beeafe469a5ddb7d60f618d | 8567438779e6af0754620a25d379c348e4cd5a5d | /chrome/test/chromedriver/chrome/navigation_tracker_unittest.cc | 91ff255a435667ef1ace19ab3e2e346bade82e5f | [
"BSD-3-Clause"
] | permissive | thngkaiyuan/chromium | c389ac4b50ccba28ee077cbf6115c41b547955ae | dab56a4a71f87f64ecc0044e97b4a8f247787a68 | refs/heads/master | 2022-11-10T02:50:29.326119 | 2017-04-08T12:28:57 | 2017-04-08T12:28:57 | 84,073,924 | 0 | 1 | BSD-3-Clause | 2022-10-25T19:47:15 | 2017-03-06T13:04:15 | null | UTF-8 | C++ | false | false | 15,284 | cc | // 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.
#include <string>
#include "base/compiler_specific.h"
#include "base/json/json_reader.h"
#include "base/values.h"
#include "chrome/test/chromedriver/chrome/browser_info.h"
#include "chrome/test/chromedriver/chrome/javascript_dialog_manager.h"
#include "chrome/test/chromedriver/chrome/navigation_tracker.h"
#include "chrome/test/chromedriver/chrome/status.h"
#include "chrome/test/chromedriver/chrome/stub_devtools_client.h"
#include "chrome/test/chromedriver/net/timeout.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace {
void AssertPendingState(NavigationTracker* tracker,
const std::string& frame_id,
bool expected_is_pending) {
bool is_pending = !expected_is_pending;
ASSERT_EQ(
kOk, tracker->IsPendingNavigation(frame_id, nullptr, &is_pending).code());
ASSERT_EQ(expected_is_pending, is_pending);
}
class DeterminingLoadStateDevToolsClient : public StubDevToolsClient {
public:
DeterminingLoadStateDevToolsClient(
bool has_empty_base_url,
bool is_loading,
const std::string& send_event_first,
base::DictionaryValue* send_event_first_params)
: has_empty_base_url_(has_empty_base_url),
is_loading_(is_loading),
send_event_first_(send_event_first),
send_event_first_params_(send_event_first_params) {}
~DeterminingLoadStateDevToolsClient() override {}
Status SendCommandAndGetResult(
const std::string& method,
const base::DictionaryValue& params,
std::unique_ptr<base::DictionaryValue>* result) override {
if (method == "DOM.getDocument") {
base::DictionaryValue result_dict;
if (has_empty_base_url_)
result_dict.SetString("root.baseURL", std::string());
else
result_dict.SetString("root.baseURL", "http://test");
result->reset(result_dict.DeepCopy());
return Status(kOk);
} else if (method == "Runtime.evaluate") {
std::string expression;
if (params.GetString("expression", &expression) && expression == "1") {
base::DictionaryValue result_dict;
result_dict.SetInteger("result.value", 1);
result->reset(result_dict.DeepCopy());
return Status(kOk);
}
}
if (send_event_first_.length()) {
for (DevToolsEventListener* listener : listeners_) {
Status status = listener->OnEvent(
this, send_event_first_, *send_event_first_params_);
if (status.IsError())
return status;
}
}
base::DictionaryValue result_dict;
result_dict.SetBoolean("result.value", is_loading_);
result->reset(result_dict.DeepCopy());
return Status(kOk);
}
private:
bool has_empty_base_url_;
bool is_loading_;
std::string send_event_first_;
base::DictionaryValue* send_event_first_params_;
};
} // namespace
TEST(NavigationTracker, FrameLoadStartStop) {
base::DictionaryValue dict;
DeterminingLoadStateDevToolsClient client(false, true, std::string(), &dict);
BrowserInfo browser_info;
JavaScriptDialogManager dialog_manager(&client);
NavigationTracker tracker(&client, &browser_info, &dialog_manager);
base::DictionaryValue params;
params.SetString("frameId", "f");
ASSERT_EQ(
kOk, tracker.OnEvent(&client, "Page.frameStartedLoading", params).code());
ASSERT_NO_FATAL_FAILURE(AssertPendingState(&tracker, "f", true));
ASSERT_EQ(
kOk, tracker.OnEvent(&client, "Page.frameStoppedLoading", params).code());
ASSERT_NO_FATAL_FAILURE(AssertPendingState(&tracker, "f", false));
}
// When a frame fails to load due to (for example) a DNS resolution error, we
// can sometimes see two Page.frameStartedLoading events with only a single
// Page.frameStoppedLoading event.
TEST(NavigationTracker, FrameLoadStartStartStop) {
base::DictionaryValue dict;
DeterminingLoadStateDevToolsClient client(false, true, std::string(), &dict);
BrowserInfo browser_info;
JavaScriptDialogManager dialog_manager(&client);
NavigationTracker tracker(&client, &browser_info, &dialog_manager);
base::DictionaryValue params;
params.SetString("frameId", "f");
ASSERT_EQ(
kOk, tracker.OnEvent(&client, "Page.frameStartedLoading", params).code());
ASSERT_NO_FATAL_FAILURE(AssertPendingState(&tracker, "f", true));
ASSERT_EQ(
kOk, tracker.OnEvent(&client, "Page.frameStartedLoading", params).code());
ASSERT_NO_FATAL_FAILURE(AssertPendingState(&tracker, "f", true));
ASSERT_EQ(
kOk, tracker.OnEvent(&client, "Page.frameStoppedLoading", params).code());
ASSERT_NO_FATAL_FAILURE(AssertPendingState(&tracker, "f", false));
}
TEST(NavigationTracker, MultipleFramesLoad) {
base::DictionaryValue dict;
DeterminingLoadStateDevToolsClient client(false, true, std::string(), &dict);
BrowserInfo browser_info;
JavaScriptDialogManager dialog_manager(&client);
NavigationTracker tracker(&client, &browser_info, &dialog_manager);
base::DictionaryValue params;
// pending_frames_set_.size() == 0
params.SetString("frameId", "1");
ASSERT_EQ(
kOk, tracker.OnEvent(&client, "Page.frameStartedLoading", params).code());
// pending_frames_set_.size() == 1
ASSERT_NO_FATAL_FAILURE(AssertPendingState(&tracker, "1", true));
params.SetString("frameId", "2");
ASSERT_EQ(
kOk, tracker.OnEvent(&client, "Page.frameStartedLoading", params).code());
// pending_frames_set_.size() == 2
ASSERT_NO_FATAL_FAILURE(AssertPendingState(&tracker, "2", true));
params.SetString("frameId", "2");
ASSERT_EQ(
kOk, tracker.OnEvent(&client, "Page.frameStoppedLoading", params).code());
// pending_frames_set_.size() == 1
ASSERT_NO_FATAL_FAILURE(AssertPendingState(&tracker, "2", true));
params.SetString("frameId", "1");
ASSERT_EQ(
kOk, tracker.OnEvent(&client, "Page.frameStoppedLoading", params).code());
// pending_frames_set_.size() == 0
ASSERT_NO_FATAL_FAILURE(AssertPendingState(&tracker, "1", false));
params.SetString("frameId", "3");
ASSERT_EQ(
kOk, tracker.OnEvent(&client, "Page.frameStoppedLoading", params).code());
// pending_frames_set_.size() == 0
ASSERT_NO_FATAL_FAILURE(AssertPendingState(&tracker, "3", false));
ASSERT_EQ(
kOk, tracker.OnEvent(&client, "Page.frameStartedLoading", params).code());
// pending_frames_set_.size() == 1
ASSERT_NO_FATAL_FAILURE(AssertPendingState(&tracker, "3", true));
}
TEST(NavigationTracker, NavigationScheduledThenLoaded) {
base::DictionaryValue dict;
DeterminingLoadStateDevToolsClient client(false, true, std::string(), &dict);
BrowserInfo browser_info;
JavaScriptDialogManager dialog_manager(&client);
NavigationTracker tracker(
&client, NavigationTracker::kNotLoading, &browser_info, &dialog_manager);
base::DictionaryValue params;
params.SetString("frameId", "f");
base::DictionaryValue params_scheduled;
params_scheduled.SetInteger("delay", 0);
params_scheduled.SetString("frameId", "f");
ASSERT_EQ(
kOk,
tracker.OnEvent(
&client, "Page.frameScheduledNavigation", params_scheduled).code());
ASSERT_NO_FATAL_FAILURE(AssertPendingState(&tracker, "f", true));
ASSERT_EQ(
kOk, tracker.OnEvent(&client, "Page.frameStartedLoading", params).code());
ASSERT_NO_FATAL_FAILURE(AssertPendingState(&tracker, "f", true));
ASSERT_EQ(
kOk,
tracker.OnEvent(&client, "Page.frameClearedScheduledNavigation", params)
.code());
ASSERT_NO_FATAL_FAILURE(AssertPendingState(&tracker, "f", true));
ASSERT_EQ(
kOk, tracker.OnEvent(&client, "Page.frameStoppedLoading", params).code());
ASSERT_NO_FATAL_FAILURE(AssertPendingState(&tracker, "f", false));
}
TEST(NavigationTracker, NavigationScheduledForOtherFrame) {
base::DictionaryValue dict;
DeterminingLoadStateDevToolsClient client(false, true, std::string(), &dict);
BrowserInfo browser_info;
JavaScriptDialogManager dialog_manager(&client);
NavigationTracker tracker(
&client, NavigationTracker::kNotLoading, &browser_info, &dialog_manager);
base::DictionaryValue params_scheduled;
params_scheduled.SetInteger("delay", 0);
params_scheduled.SetString("frameId", "other");
ASSERT_EQ(
kOk,
tracker.OnEvent(
&client, "Page.frameScheduledNavigation", params_scheduled).code());
ASSERT_NO_FATAL_FAILURE(AssertPendingState(&tracker, "f", false));
}
TEST(NavigationTracker, NavigationScheduledThenCancelled) {
base::DictionaryValue dict;
DeterminingLoadStateDevToolsClient client(false, true, std::string(), &dict);
BrowserInfo browser_info;
JavaScriptDialogManager dialog_manager(&client);
NavigationTracker tracker(
&client, NavigationTracker::kNotLoading, &browser_info, &dialog_manager);
base::DictionaryValue params;
params.SetString("frameId", "f");
base::DictionaryValue params_scheduled;
params_scheduled.SetInteger("delay", 0);
params_scheduled.SetString("frameId", "f");
ASSERT_EQ(
kOk,
tracker.OnEvent(
&client, "Page.frameScheduledNavigation", params_scheduled).code());
ASSERT_NO_FATAL_FAILURE(AssertPendingState(&tracker, "f", true));
ASSERT_EQ(
kOk,
tracker.OnEvent(&client, "Page.frameClearedScheduledNavigation", params)
.code());
ASSERT_NO_FATAL_FAILURE(AssertPendingState(&tracker, "f", false));
}
TEST(NavigationTracker, NavigationScheduledTooFarAway) {
base::DictionaryValue dict;
DeterminingLoadStateDevToolsClient client(false, true, std::string(), &dict);
BrowserInfo browser_info;
JavaScriptDialogManager dialog_manager(&client);
NavigationTracker tracker(
&client, NavigationTracker::kNotLoading, &browser_info, &dialog_manager);
base::DictionaryValue params_scheduled;
params_scheduled.SetInteger("delay", 10);
params_scheduled.SetString("frameId", "f");
ASSERT_EQ(
kOk,
tracker.OnEvent(
&client, "Page.frameScheduledNavigation", params_scheduled).code());
ASSERT_NO_FATAL_FAILURE(AssertPendingState(&tracker, "f", false));
}
TEST(NavigationTracker, DiscardScheduledNavigationsOnMainFrameCommit) {
base::DictionaryValue dict;
DeterminingLoadStateDevToolsClient client(false, true, std::string(), &dict);
BrowserInfo browser_info;
JavaScriptDialogManager dialog_manager(&client);
NavigationTracker tracker(
&client, NavigationTracker::kNotLoading, &browser_info, &dialog_manager);
base::DictionaryValue params_scheduled;
params_scheduled.SetString("frameId", "subframe");
params_scheduled.SetInteger("delay", 0);
Status status = tracker.OnEvent(&client,
"Page.frameScheduledNavigation",
params_scheduled);
ASSERT_EQ(kOk, status.code()) << status.message();
ASSERT_NO_FATAL_FAILURE(AssertPendingState(&tracker, "subframe", true));
base::DictionaryValue params_navigated;
params_navigated.SetString("frame.parentId", "something");
params_navigated.SetString("frame.name", std::string());
params_navigated.SetString("frame.url", "http://abc.xyz");
status = tracker.OnEvent(&client, "Page.frameNavigated", params_navigated);
ASSERT_EQ(kOk, status.code()) << status.message();
ASSERT_NO_FATAL_FAILURE(AssertPendingState(&tracker, "subframe", true));
params_navigated.Clear();
params_navigated.SetString("frame.id", "something");
params_navigated.SetString("frame.url", "http://abc.xyz");
status = tracker.OnEvent(&client, "Page.frameNavigated", params_navigated);
ASSERT_EQ(kOk, status.code()) << status.message();
ASSERT_NO_FATAL_FAILURE(AssertPendingState(&tracker, "subframe", false));
}
namespace {
class FailToEvalScriptDevToolsClient : public StubDevToolsClient {
public:
FailToEvalScriptDevToolsClient() : is_dom_getDocument_requested_(false) {}
~FailToEvalScriptDevToolsClient() override {}
Status SendCommandAndGetResult(
const std::string& method,
const base::DictionaryValue& params,
std::unique_ptr<base::DictionaryValue>* result) override {
if (!is_dom_getDocument_requested_ && method == "DOM.getDocument") {
is_dom_getDocument_requested_ = true;
base::DictionaryValue result_dict;
result_dict.SetString("root.baseURL", "http://test");
result->reset(result_dict.DeepCopy());
return Status(kOk);
}
EXPECT_STREQ("Runtime.evaluate", method.c_str());
return Status(kUnknownError, "failed to eval script");
}
private:
bool is_dom_getDocument_requested_;
};
} // namespace
TEST(NavigationTracker, UnknownStateFailsToDetermineState) {
FailToEvalScriptDevToolsClient client;
BrowserInfo browser_info;
JavaScriptDialogManager dialog_manager(&client);
NavigationTracker tracker(&client, &browser_info, &dialog_manager);
bool is_pending;
ASSERT_EQ(kUnknownError,
tracker.IsPendingNavigation("f", nullptr, &is_pending).code());
}
TEST(NavigationTracker, UnknownStatePageNotLoadAtAll) {
base::DictionaryValue params;
DeterminingLoadStateDevToolsClient client(
true, true, std::string(), ¶ms);
BrowserInfo browser_info;
JavaScriptDialogManager dialog_manager(&client);
NavigationTracker tracker(&client, &browser_info, &dialog_manager);
ASSERT_NO_FATAL_FAILURE(AssertPendingState(&tracker, "f", true));
}
TEST(NavigationTracker, UnknownStateForcesStart) {
base::DictionaryValue params;
DeterminingLoadStateDevToolsClient client(
false, true, std::string(), ¶ms);
BrowserInfo browser_info;
JavaScriptDialogManager dialog_manager(&client);
NavigationTracker tracker(&client, &browser_info, &dialog_manager);
ASSERT_NO_FATAL_FAILURE(AssertPendingState(&tracker, "f", true));
}
TEST(NavigationTracker, UnknownStateForcesStartReceivesStop) {
base::DictionaryValue params;
params.SetString("frameId", "f");
DeterminingLoadStateDevToolsClient client(
false, true, "Page.frameStoppedLoading", ¶ms);
BrowserInfo browser_info;
JavaScriptDialogManager dialog_manager(&client);
NavigationTracker tracker(&client, &browser_info, &dialog_manager);
ASSERT_NO_FATAL_FAILURE(AssertPendingState(&tracker, "f", false));
}
TEST(NavigationTracker, OnSuccessfulNavigate) {
base::DictionaryValue params;
DeterminingLoadStateDevToolsClient client(
false, true, std::string(), ¶ms);
BrowserInfo browser_info;
std::string version_string = "{\"Browser\": \"Chrome/44.0.2403.125\","
" \"WebKit-Version\": \"537.36 (@199461)\"}";
ASSERT_TRUE(ParseBrowserInfo(version_string, &browser_info).IsOk());
JavaScriptDialogManager dialog_manager(&client);
NavigationTracker tracker(
&client, NavigationTracker::kNotLoading, &browser_info, &dialog_manager);
base::DictionaryValue result;
result.SetString("frameId", "f");
tracker.OnCommandSuccess(&client, "Page.navigate", result, Timeout());
ASSERT_NO_FATAL_FAILURE(AssertPendingState(&tracker, "f", true));
tracker.OnEvent(&client, "Page.loadEventFired", params);
ASSERT_NO_FATAL_FAILURE(AssertPendingState(&tracker, "f", true));
params.Clear();
params.SetString("frameId", "f");
tracker.OnEvent(&client, "Page.frameStoppedLoading", params);
ASSERT_NO_FATAL_FAILURE(AssertPendingState(&tracker, "f", false));
}
| [
"hedonist.ky@gmail.com"
] | hedonist.ky@gmail.com |
db85718c153201f2c223f2cdcacea272481788cd | 15bb20fa36c1fb297db2c5ae805bb57039d31cb0 | /src/schemas/f142/DataFromPVStruct.h | 6dfcf9b6d24389591f41208df704866a5480b2b2 | [
"BSD-2-Clause"
] | permissive | ess-dmsc/forward-epics-to-kafka | a7cceb3bf0b6f8846aef45567a6a32cc3eddafd3 | 46e1cfff0a3792b4e70ec5c58c2e56c941da5d5c | refs/heads/master | 2021-05-23T04:43:55.616448 | 2021-05-05T15:03:05 | 2021-05-05T15:03:05 | 81,432,248 | 1 | 5 | BSD-2-Clause | 2021-05-06T12:28:55 | 2017-02-09T09:19:49 | C++ | UTF-8 | C++ | false | false | 591 | h | // SPDX-License-Identifier: BSD-2-Clause
//
// This code has been produced by the European Spallation Source
// and its partner institutes under the BSD 2 Clause License.
//
// See LICENSE.md at the top level for license information.
//
// Screaming Udder! https://esss.se
#pragma once
#include <f142_logdata_generated.h>
#include <pv/pvData.h>
namespace FlatBufs {
namespace f142 {
AlarmStatus
getAlarmStatus(epics::pvData::PVStructurePtr const &PVStructureField);
AlarmSeverity
getAlarmSeverity(epics::pvData::PVStructurePtr const &PVStructureField);
}
}
| [
"matthew.d.jones@tessella.com"
] | matthew.d.jones@tessella.com |
dec11c940a94231e27dc7d435fa6032e2cc14b24 | d589ae0e355e33261bcd20d2bf0f5ef901ae7c37 | /๊ณผ์ธ/0211.cpp | 515849acca1727ac6d5577f641a0ff7cc53d48ff | [] | no_license | Upit63/ClassKYT | bbc20f98bdb36dfc9a068c9bfda6ad44afdb2841 | 4afcd1822d34e7d3316db3fdeed2b5e5102c7df7 | refs/heads/master | 2021-01-22T18:15:44.371836 | 2017-05-20T06:48:21 | 2017-05-20T06:48:21 | 85,073,155 | 0 | 0 | null | null | null | null | UHC | C++ | false | false | 1,568 | cpp | #include <iostream>
#include <fstream>
#include <vector>
#include <Windows.h>
using namespace std;
int main()
{
std::vector<char> v;
ifstream fin;
fin.open("the.txt",ios::binary);
if (true == fin.fail())
{
std::cout << "not ifstream find" << std::endl;
return 0;
}
char c = NULL;
char msg[20] = { NULL };
int iCount = 0;
int i = 0;
char enter[4] = { NULL };
char arrThat[3] = { 't','h','a' };
char *arrpThat[3] = { nullptr };
//getline '/r' ๋์ฌ๋๊น์ง ์ฝ๋๋ค.
//get charํฌ๊ธฐ๋งํผ ํ์นธ์ฉ ์ฝ์
// .operator>>(char c) get(char)์ด๋ ๋น์ทํ๊ฒ ์ฝ๋๋ค.
while (fin.get(c))
{
if (c == ' ')
{
fin.get(c);
v.push_back(c);
if (c == 't' || c == 'T')
{
//enter[0] = c;
fin.get(c);
v.push_back(c);
if (c == 'h' || c == 'H')
{
//enter[1] = c;
fin.get(c);
v.push_back(c);
if (c == 'e' || c == 'E')
{
//enter[2] = c;
fin.get(c);
v.push_back(c);
if (c == ' ')
{
//++iCount;
}
//v.push_back(c);
}
}
}
}
//v.push_back(c);
//else
//{
// while (fin.get(c))
// {
// if (c == ' ')
// {
// break;
// }
//
// }
//}
}
fin.close();
std::cout << "the: " << iCount << std::endl;
return 0;
ofstream out("์
๋กํ์ฆ์๋ชจํ.txt", ios::binary);
if (out.fail()==true)
{
std::cout << "not ofstream find" << std::endl;
return 0;
}
/*for (auto d : v)
{
out << d <<",";
}*/
out.close();
}
///<summary>
///๋ด์ฉ
///<summary>
//์ฃผ์ ์ฒ๋ฆฌํ ํจ์
| [
"์ง์
@์ง์
-PC"
] | ์ง์
@์ง์
-PC |
7f6748107a3f06ca60bbe2b701092fe6d66e78d0 | 19907e496cfaf4d59030ff06a90dc7b14db939fc | /POC/oracle_dapp/node_modules/wrtc/third_party/webrtc/include/chromium/src/cc/layers/nine_patch_layer_impl.h | 539d8e717aed319b6c88bfc6c1e73f727b3a9308 | [
"BSD-2-Clause"
] | permissive | ATMatrix/demo | c10734441f21e24b89054842871a31fec19158e4 | e71a3421c75ccdeac14eafba38f31cf92d0b2354 | refs/heads/master | 2020-12-02T20:53:29.214857 | 2017-08-28T05:49:35 | 2017-08-28T05:49:35 | 96,223,899 | 8 | 4 | null | 2017-08-28T05:49:36 | 2017-07-04T13:59:26 | JavaScript | UTF-8 | C++ | false | false | 3,180 | h | // Copyright 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef CC_LAYERS_NINE_PATCH_LAYER_IMPL_H_
#define CC_LAYERS_NINE_PATCH_LAYER_IMPL_H_
#include <string>
#include "base/macros.h"
#include "cc/base/cc_export.h"
#include "cc/layers/layer_impl.h"
#include "cc/layers/ui_resource_layer_impl.h"
#include "cc/resources/resource_provider.h"
#include "cc/resources/ui_resource_client.h"
#include "ui/gfx/geometry/rect.h"
#include "ui/gfx/geometry/size.h"
namespace base {
class DictionaryValue;
}
namespace cc {
class CC_EXPORT NinePatchLayerImpl : public UIResourceLayerImpl {
public:
static scoped_ptr<NinePatchLayerImpl> Create(LayerTreeImpl* tree_impl,
int id) {
return make_scoped_ptr(new NinePatchLayerImpl(tree_impl, id));
}
~NinePatchLayerImpl() override;
// The bitmap stretches out the bounds of the layer. The following picture
// illustrates the parameters associated with the dimensions.
//
// Layer space layout Bitmap space layout
//
// ------------------------ ~~~~~~~~~~ W ~~~~~~~~~~
// | : | : : |
// | C | : Y |
// | : | : : |
// | ------------ | :~~X~~------------ |
// | | | | : | : |
// | | | | : | : |
// |~~A~~| |~~B~~| H | Q |
// | | | | : | : |
// | ------------ | : ~~~~~P~~~~~ |
// | : | : |
// | D | : |
// | : | : |
// ------------------------ ------------------------
//
// |image_bounds| = (W, H)
// |image_aperture| = (X, Y, P, Q)
// |border| = (A, C, A + B, C + D)
// |fill_center| indicates whether to draw the center quad or not.
void SetLayout(const gfx::Rect& image_aperture,
const gfx::Rect& border,
bool fill_center,
bool nearest_neighbor);
scoped_ptr<LayerImpl> CreateLayerImpl(LayerTreeImpl* tree_impl) override;
void PushPropertiesTo(LayerImpl* layer) override;
void AppendQuads(RenderPass* render_pass,
AppendQuadsData* append_quads_data) override;
base::DictionaryValue* LayerTreeAsJson() const override;
protected:
NinePatchLayerImpl(LayerTreeImpl* tree_impl, int id);
private:
const char* LayerTypeAsString() const override;
void CheckGeometryLimitations();
// The transparent center region that shows the parent layer's contents in
// image space.
gfx::Rect image_aperture_;
// An inset border that the patches will be mapped to.
gfx::Rect border_;
bool fill_center_;
bool nearest_neighbor_;
DISALLOW_COPY_AND_ASSIGN(NinePatchLayerImpl);
};
} // namespace cc
#endif // CC_LAYERS_NINE_PATCH_LAYER_IMPL_H_
| [
"steven.jun.liu@qq.com"
] | steven.jun.liu@qq.com |
1cada43bfd62a0ec20ad30d50fbf891635c7b6e8 | b00118e894b439919ed3d96c68889a8282963cad | /compiler/optimizing/optimization.cc | 1e68ca2802589fb5056f10a3c62e80c260ce45fc | [
"Apache-2.0",
"NCSA"
] | permissive | BenzoRoms/art | f04ad0c8126f533dfa68739878c5e0a0c1b2559c | 5575513f1529ea43371a6d4d9a495b57e7d68409 | refs/heads/master | 2021-01-23T21:29:31.807637 | 2017-08-26T01:07:46 | 2017-08-26T01:07:46 | 59,618,203 | 0 | 6 | null | null | null | null | UTF-8 | C++ | false | false | 684 | cc | /*
* Copyright (C) 2014 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "optimization.h"
namespace art {
} // namespace art
| [
"rpl@google.com"
] | rpl@google.com |
368ec28e80ca0e220e7b3a7aea958ab34ddaa205 | 87aba51b1f708b47d78b5c4180baf731d752e26d | /Replication/DataFileSystem/PRODUCT_SOURCE_CODE/itk/Modules/Filtering/ImageFilterBase/include/itkMaskNeighborhoodOperatorImageFilter.h | e0f18d1faa4fbe03efad97342df2ab6dbde8c860 | [] | no_license | jstavr/Architecture-Relation-Evaluator | 12c225941e9a4942e83eb6d78f778c3cf5275363 | c63c056ee6737a3d90fac628f2bc50b85c6bd0dc | refs/heads/master | 2020-12-31T05:10:08.774893 | 2016-05-14T16:09:40 | 2016-05-14T16:09:40 | 58,766,508 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,371 | h | /*=========================================================================
*
* Copyright Insight Software Consortium
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0.txt
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*=========================================================================*/
#ifndef __itkMaskNeighborhoodOperatorImageFilter_h
#define __itkMaskNeighborhoodOperatorImageFilter_h
#include "itkNeighborhoodOperatorImageFilter.h"
namespace itk
{
/** \class MaskNeighborhoodOperatorImageFilter
* \brief Applies a single NeighborhoodOperator to an image,
* processing only those pixels that are under a mask.
*
* This filter calculates successive inner products between a single
* NeighborhoodOperator and a NeighborhoodIterator, which is swept
* across every pixel that is set in the input mask. If no mask is
* given, this filter is equivalent to its superclass. Output pixels
* that are outside of the mask will be set to DefaultValue if
* UseDefaultValue is true (default). Otherwise, they will be set to
* the value of the input pixel.
*
* \ingroup ImageFilters
*
* \sa Image
* \sa Neighborhood
* \sa NeighborhoodOperator
* \sa NeighborhoodOperatorImageFilter
* \sa NeighborhoodIterator
* \ingroup ITKImageFilterBase
*
* \wiki
* \wikiexample{Images/MaskNeighborhoodOperatorImageFilter,Apply a kernel to every pixel in an image that is non-zero in a mask}
* \endwiki
*/
template< typename TInputImage, typename TMaskImage, typename TOutputImage, typename TOperatorValueType =
typename TOutputImage::PixelType >
class MaskNeighborhoodOperatorImageFilter:
public NeighborhoodOperatorImageFilter< TInputImage, TOutputImage, TOperatorValueType >
{
public:
/** Standard "Self" & Superclass typedef. */
typedef MaskNeighborhoodOperatorImageFilter Self;
typedef NeighborhoodOperatorImageFilter<
TInputImage, TOutputImage, TOperatorValueType > Superclass;
typedef SmartPointer< Self > Pointer;
typedef SmartPointer< const Self > ConstPointer;
/** Method for creation through the object factory. */
itkNewMacro(Self);
/** Run-time type information (and related methods). */
itkTypeMacro(MaskNeighborhoodOperatorImageFilter, NeighborhoodOperatorImageFilter);
/** Extract some information from the image types. Dimensionality
* of the two images is assumed to be the same. */
typedef typename TOutputImage::PixelType OutputPixelType;
typedef typename TOutputImage::InternalPixelType OutputInternalPixelType;
typedef typename TInputImage::PixelType InputPixelType;
typedef typename TInputImage::InternalPixelType InputInternalPixelType;
typedef typename TMaskImage::PixelType MaskPixelType;
typedef typename TMaskImage::InternalPixelType MaskInternalPixelType;
/** Extract some information from the image types. Dimensionality
* of the two images is assumed to be the same. */
itkStaticConstMacro(ImageDimension, unsigned int,
TOutputImage::ImageDimension);
itkStaticConstMacro(InputImageDimension, unsigned int,
TInputImage::ImageDimension);
itkStaticConstMacro(MaskImageDimension, unsigned int,
TMaskImage::ImageDimension);
/** Image typedef support. */
typedef TInputImage InputImageType;
typedef TMaskImage MaskImageType;
typedef TOutputImage OutputImageType;
typedef typename InputImageType::Pointer InputImagePointer;
typedef typename MaskImageType::Pointer MaskImagePointer;
/** Typedef for generic boundary condition pointer. */
typedef ImageBoundaryCondition< OutputImageType > *
ImageBoundaryConditionPointerType;
/** Superclass typedefs. */
typedef typename Superclass::OutputImageRegionType OutputImageRegionType;
typedef typename Superclass::OperatorValueType OperatorValueType;
/** Neighborhood types */
typedef typename Superclass::OutputNeighborhoodType OutputNeighborhoodType;
/** Set the mask image. Using a mask is optional. When a mask is
* specified, the normalized correlation is only calculated for
* those pixels under the mask. */
void SetMaskImage(const TMaskImage *mask);
/** Get the mask image. Using a mask is optional. When a mask is
* specified, the normalized correlation is only calculated for
* those pixels under the mask. */
const TMaskImage * GetMaskImage() const;
/** Set the output value for the pixels that are not under the mask.
* Defaults to zero.
*/
itkSetMacro(DefaultValue, OutputPixelType);
/** Get the output value for the pixels that are not under the
* mask. */
itkGetConstMacro(DefaultValue, OutputPixelType);
/** Set the UseDefaultValue flag. If true, the pixels outside the
* mask will e set to m_DefaultValue. Otherwise, they will be set
* to the input pixel. */
itkSetMacro(UseDefaultValue, bool);
/** Get the UseDefaultValue flag. */
itkGetConstReferenceMacro(UseDefaultValue, bool);
/** Turn on and off the UseDefaultValue flag. */
itkBooleanMacro(UseDefaultValue);
#ifdef ITK_USE_CONCEPT_CHECKING
// Begin concept checking
itkConceptMacro( OutputEqualityComparableCheck,
( Concept::EqualityComparable< OutputPixelType > ) );
itkConceptMacro( SameDimensionCheck1,
( Concept::SameDimension< InputImageDimension, ImageDimension > ) );
itkConceptMacro( SameDimensionCheck2,
( Concept::SameDimension< InputImageDimension, MaskImageDimension > ) );
itkConceptMacro( InputConvertibleToOutputCheck,
( Concept::Convertible< InputPixelType, OutputPixelType > ) );
itkConceptMacro( OperatorConvertibleToOutputCheck,
( Concept::Convertible< OperatorValueType, OutputPixelType > ) );
itkConceptMacro( OutputOStreamWritable,
( Concept::OStreamWritable< OutputPixelType > ) );
// End concept checking
#endif
protected:
MaskNeighborhoodOperatorImageFilter():m_DefaultValue(NumericTraits< OutputPixelType >::Zero),
m_UseDefaultValue(true) {}
virtual ~MaskNeighborhoodOperatorImageFilter() {}
void PrintSelf(std::ostream & os, Indent indent) const;
/** MaskNeighborhoodOperatorImageFilter needs to request enough of an
* input image to account for template size. The input requested
* region is expanded by the radius of the template. If the request
* extends past the LargestPossibleRegion for the input, the request
* is cropped by the LargestPossibleRegion. */
void GenerateInputRequestedRegion()
throw ( InvalidRequestedRegionError );
/** MaskNeighborhoodOperatorImageFilter can be implemented as a
* multithreaded filter. Therefore, this implementation provides a
* ThreadedGenerateData() routine which is called for each
* processing thread. The output image data is allocated
* automatically by the superclass prior to calling
* ThreadedGenerateData(). ThreadedGenerateData can only write to
* the portion of the output image specified by the parameter
* "outputRegionForThread"
*
* \sa ImageToImageFilter::ThreadedGenerateData(),
* ImageToImageFilter::GenerateData() */
void ThreadedGenerateData(const OutputImageRegionType & outputRegionForThread,
ThreadIdType threadId);
private:
MaskNeighborhoodOperatorImageFilter(const Self &); //purposely not implemented
void operator=(const Self &); //purposely not implemented
OutputPixelType m_DefaultValue;
bool m_UseDefaultValue;
};
} // end namespace itk
#ifndef ITK_MANUAL_INSTANTIATION
#include "itkMaskNeighborhoodOperatorImageFilter.hxx"
#endif
#endif
| [
"jstavr2@gmail.com"
] | jstavr2@gmail.com |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.