blob_id
stringlengths 40
40
| directory_id
stringlengths 40
40
| path
stringlengths 2
247
| content_id
stringlengths 40
40
| detected_licenses
listlengths 0
57
| license_type
stringclasses 2
values | repo_name
stringlengths 4
111
| snapshot_id
stringlengths 40
40
| revision_id
stringlengths 40
40
| branch_name
stringlengths 4
58
| visit_date
timestamp[ns]date 2015-07-25 18:16:41
2023-09-06 10:45:08
| revision_date
timestamp[ns]date 1970-01-14 14:03:36
2023-09-06 06:22:19
| committer_date
timestamp[ns]date 1970-01-14 14:03:36
2023-09-06 06:22:19
| github_id
int64 3.89k
689M
⌀ | star_events_count
int64 0
209k
| fork_events_count
int64 0
110k
| gha_license_id
stringclasses 25
values | gha_event_created_at
timestamp[ns]date 2012-06-07 00:51:45
2023-09-14 21:58:52
⌀ | gha_created_at
timestamp[ns]date 2008-03-27 23:40:48
2023-08-24 19:49:39
⌀ | gha_language
stringclasses 159
values | src_encoding
stringclasses 34
values | language
stringclasses 1
value | is_vendor
bool 1
class | is_generated
bool 2
classes | length_bytes
int64 7
10.5M
| extension
stringclasses 111
values | filename
stringlengths 1
195
| text
stringlengths 7
10.5M
|
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
8001e12b96902ae47d40ebe66f3bf3442fa24875
|
20b49a6ef1fa417d67abef2d29a598c9e41c478e
|
/CodeForces/Lockout/Round 14/C.cpp
|
0b5b800c466969a730342de77240d74e1d5849ac
|
[] |
no_license
|
switchpiggy/Competitive_Programming
|
956dac4a71fdf65de2959dd142a2032e2f0710e1
|
beaaae4ece70889b0af1494d68c630a6e053558a
|
refs/heads/master
| 2023-04-15T19:13:12.348433
| 2021-04-04T06:12:29
| 2021-04-04T06:12:29
| 290,905,106
| 1
| 3
| null | 2020-10-05T20:16:53
| 2020-08-27T23:38:48
|
C++
|
UTF-8
|
C++
| false
| false
| 861
|
cpp
|
C.cpp
|
#include <bits/stdc++.h>
using namespace std;
typedef long long int ll;
typedef long double ld;
#define benq queue
#define pbenq priority_queue
#define all(x) x.begin(), x.end()
#define sz(x) (ll)x.size()
#define m1(x) memset(x, 1, sizeof(x))
#define m0(x) memset(x, 0, sizeof(x))
#define inf(x) memset(x, 0x3f, sizeof(x))
#define flout cout << fixed << setprecision(12)
ll m, x, y, c[107];
int main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
cin >> m;
for(ll i = 0; i < m; ++i) cin >> c[i];
cin >> x >> y;
for(ll i = 1; i <= m; ++i) {
ll a = 0,b = 0;
for(ll j = 0; j < m; ++j) {
if(j + 1 >= i) b += c[j];
else a += c[j];
}
if(a >= x && a <= y && b >= x && b <= y) {
cout << i << '\n';
return 0;
}
}
cout << 0 << '\n';
return 0;
}
|
4f1cd525269e91c0775d11ea619f6cc0cee579e4
|
e3d7cdb7cfb0140921737517024c2f85b5cb66bb
|
/Project1/InputManager.h
|
6eaed9864b7ad2f9e10ad2d9ef40043c75adb80a
|
[] |
no_license
|
scabsy/ICT397---Assignment-1
|
07df76a1208803e852d623784a94fdc944758db8
|
71729658e4fcb802d1381712af8397dcc59e8c62
|
refs/heads/master
| 2021-01-20T02:38:26.344620
| 2017-06-02T14:33:59
| 2017-06-02T14:33:59
| 89,433,633
| 0
| 1
| null | 2017-06-02T14:34:00
| 2017-04-26T03:28:04
|
C++
|
UTF-8
|
C++
| false
| false
| 114
|
h
|
InputManager.h
|
#pragma once
class InputManager
{
public:
InputManager(void);
~InputManager(void);
void KeyPressed(void);
};
|
e675f16520f53fa895d1447f883b4be16749260b
|
a6df040949fc4b45b3350a9514099900b91384d7
|
/cpp/api/include/trtorch/logging.h
|
e0a892113ca9bbac963cb824e043d479bc6e5d29
|
[
"BSD-3-Clause",
"BSD-2-Clause"
] |
permissive
|
bytedance/TRTorch
|
f1cf760f40cd6c99b9f36c0d356b3c55cae909cb
|
41130568fe46aa9b35d8e0dba5f014ef4d484666
|
refs/heads/master
| 2023-03-29T01:06:13.469456
| 2021-03-10T08:10:08
| 2021-03-10T08:10:08
| 297,588,215
| 10
| 3
|
BSD-3-Clause
| 2021-03-11T03:03:17
| 2020-09-22T08:42:23
|
Jupyter Notebook
|
UTF-8
|
C++
| false
| false
| 2,004
|
h
|
logging.h
|
/*
* Copyright (c) NVIDIA Corporation.
* All rights reserved.
*
* This library is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree.
*/
#pragma once
#include <string>
#include "trtorch/macros.h"
namespace trtorch {
namespace logging {
/**
* Emum for setting message severity
*/
enum Level {
/// Only print messages for internal errors
kINTERNAL_ERROR,
/// Print all internal errors and errors (default)
kERROR,
/// Print warnings and errors
kWARNING,
/// Print all info, warnings and errors
kINFO,
/// Print all debug info, info, warnings and errors
kDEBUG,
/// Print everything including the intermediate graphs of the lowering phase
kGRAPH,
};
// Are these ones necessary for the user?
TRTORCH_API std::string get_logging_prefix();
TRTORCH_API void set_logging_prefix(std::string prefix);
/**
* @brief Sets the level that logging information needs to be to be added to the
* log
*
* @param lvl: trtorch::logging::Level - Level that messages need to be at or
* above to be added to the log
*/
TRTORCH_API void set_reportable_log_level(Level lvl);
/**
* @brief Sets if logging prefix will be colored (helpful when debugging but not
* always supported by terminal)
*
* @param colored_output_on: bool - If the output will be colored or not
*/
TRTORCH_API void set_is_colored_output_on(bool colored_output_on);
/**
* @brief Get the current reportable log level
*
* @return TRTORCH_API get_reportable_log_level
*/
TRTORCH_API Level get_reportable_log_level();
/**
* @brief Is colored output enabled?
*
* @return TRTORCH_API get_is_colored_output_on
*/
TRTORCH_API bool get_is_colored_output_on();
/**
* @brief Adds a message to the global log
*
* @param lvl: trtorch::logging::Level - Severity of the message
* @param msg: std::string - Message to be logged
*/
// Dont know if we want this?
TRTORCH_API void log(Level lvl, std::string msg);
} // namespace logging
} // namespace trtorch
|
f1cd3965c0eedf96cfc0f36def8b27a094e27283
|
87b5bb04e2972016f939bbe371e0a85f456730f5
|
/LeetCode/P110_balanced_binary_tree.cc
|
2441063bdb3bf0649e0bdb9cc4bd072c46f0aff3
|
[] |
no_license
|
StonecutterX/DataStructureAndAlgorithm
|
9db8fd00ea067018decfe6441974998917ce4939
|
f940c653b8bc24f68d6eb8ea2141c18a3ad2ea62
|
refs/heads/master
| 2022-10-24T14:10:28.583245
| 2020-06-17T15:48:10
| 2020-06-17T15:48:10
| 237,130,514
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,088
|
cc
|
P110_balanced_binary_tree.cc
|
/**
* Given a binary tree, determine if it is height-balanced.
For this problem, a height-balanced binary tree is defined as:
a binary tree in which the left and right subtrees of every node differ in height by no more than 1.
Given the following tree [3,9,20,null,null,15,7]:
3
/ \
9 20
/ \
15 7
Return true.
Given the following tree [1,2,2,3,3,null,null,4,4]:
1
/ \
2 2
/ \
3 3
/ \
4 4
Return false.
*/
#include <iostream>
#include <vector>
using namespace std;
// 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:
bool IsBalancedFromBottomToUp(TreeNode* root) {
if (root == NULL) {
return true;
}
int height = 0;
return IsBalancedFromBottomToUp(root, height);
}
/**
* 递归的判断根节点及左右子节点是否为平衡二叉树
* 自顶向下的方式,存在height的重复计算
*/
bool isBalanced(TreeNode* root) {
if (root == NULL) {
return true;
}
return (std::abs(GetTreeHeight(root->left) - GetTreeHeight(root->right)) <= 1) && isBalanced(root->left) &&
isBalanced(root->right);
}
private:
int GetTreeHeight(TreeNode* root) {
// empty tree has height -1, as it's calculated recursively
if (root == NULL) {
return -1;
}
return 1 + max(GetTreeHeight(root->left), GetTreeHeight(root->right));
}
// 自底向上
bool IsBalancedFromBottomToUp(TreeNode* root, int& height) {
if (root == NULL) {
height = -1;
return true;
}
int left_h, right_h;
if (IsBalancedFromBottomToUp(root->left, left_h) && IsBalancedFromBottomToUp(root->right, right_h) &&
std::abs(left_h - right_h) < 2) {
height = std::max(left_h, right_h) + 1;
return true;
}
return false;
}
};
|
b90ab06e28bac91f6e49c67a888183cb1dd660aa
|
e7827b86cc03da81379f6058d37b7ea9f13f4d3a
|
/examples/websocketserver.cpp
|
e093462a6e344fd476cbeb16298813bc26f7e256
|
[
"Apache-2.0"
] |
permissive
|
jackim/kiss
|
db0ff9947084cb0c7eb1b7126b6afc4f00034e01
|
e9216dfc46c2d047eb107f04d3d99d88ec58f3b5
|
refs/heads/master
| 2020-04-28T14:08:52.281437
| 2019-04-04T12:49:34
| 2019-04-04T12:49:34
| 173,287,993
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,150
|
cpp
|
websocketserver.cpp
|
#include <loop.hpp>
#include <websocket.hpp>
#include <server.hpp>
#include <spdlog/spdlog.h>
#include <iostream>
using namespace jackim::kiss;
class Handler:public IWebSocketHandler
{
public:
Handler(Base *base)
{
_sock = new WebSocket(base , this);
}
virtual std::string onEstablished(const std::vector<std::string> &vecProtocol)
{
SPDLOG_INFO("test111");
return "test";
}
virtual void onTextFrame(const std::vector<char> &text , FrameSeq seq)
{
auto data = _sock->makeTextFrame(text , seq);
_sock->write(data.data() , data.size());
}
virtual void onCloseFrame()
{
SPDLOG_INFO("closeframe");
}
virtual void onClose()
{
SPDLOG_INFO("close");
}
private:
WebSocket *_sock;
};
int main()
{
Loop *loop = new Loop();
loop->start();
spdlog::set_pattern("[%Y-%m-%d %H:%M:%S.%e] [%t] %! - %v - %@");
auto server = new Server(loop);
server->listen("127.0.0.1" , 8080);
server->setConnectCB([](Base *base){
new Handler(base);
});
loop->join();
return 0;
}
|
5ecb3e4fe084850d1de9aab0e52611e185609ebd
|
1706a5c5394564ba9ef8d2bec24a1467024a8980
|
/mainwindow.h
|
4ecb5250f37639f619d602c75ed07b183e3a964d
|
[] |
no_license
|
daws612/KNN_Performance
|
21836c3437375bff47ad2310437a3eede953a59d
|
96fbedb6920c8b9b5386f3f6c533c75338cf9642
|
refs/heads/master
| 2020-04-27T17:03:11.357081
| 2019-03-15T22:47:40
| 2019-03-15T22:47:40
| 174,503,263
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,070
|
h
|
mainwindow.h
|
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include <QVector>
class Neighbour;
namespace Ui {
class MainWindow;
}
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = 0);
~MainWindow();
void displayColumnInfo();
void splitTrainAndTestData();
QString getPredictionOfKNeighbours(int k);
void clearUI();
void readAndCreateDataSet();
void performPrediction();
private slots:
void on_actionImport_Dataset_triggered();
void on_cbClassColumn_currentIndexChanged(int index);
void on_btnReClassify_clicked();
private:
Ui::MainWindow *ui;
QStringList columnNames;
QList<QStringList> columnKeys;
int classColumnIndex;
QVector<Neighbour*> allDataPoints;
QVector<Neighbour*> trainPoints;
QVector<Neighbour*> testPoints;
QString filename;
void performKNN();
double EuclideanDistance(QVector<double> observation, QVector<double> test);
Neighbour *createNeighbourObject(QString observation);
};
#endif // MAINWINDOW_H
|
d942946ec32918bb618c3b85ab8718bc3b63cb8a
|
bc3073755ed70dd63a7c947fec63ccce408e5710
|
/src/Game/Camera.h
|
72589be5119c7c4c80028053f323493ade6ae26f
|
[] |
no_license
|
ptrefall/ste6274gamedesign
|
9e659f7a8a4801c5eaa060ebe2d7edba9c31e310
|
7d5517aa68910877fe9aa98243f6bb2444d533c7
|
refs/heads/master
| 2016-09-07T18:42:48.012493
| 2011-10-13T23:41:40
| 2011-10-13T23:41:40
| 32,448,466
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 586
|
h
|
Camera.h
|
#pragma once
#include <glm/glm.hpp>
#include <glm/gtc/quaternion.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <glm/gtc/type_ptr.hpp>
namespace Totem { class Entity; }
class Camera
{
public:
static glm::mat4 getPerspective();
static glm::mat4 getView();
static void prepare();
static void rotate(const float &rate, const glm::vec3 &axis);
static void translate(const glm::vec3 &delta_pos);
static void setPos(const glm::vec3 &pos);
private:
static glm::vec3 position;
static glm::gtc::quaternion::quat qRotation;
static glm::mat4 view;
};
|
be9b7369d3c563816edccbb7ffc86e5956e95789
|
e634448a11f60fc974d24fc1f077943aeeba2919
|
/examples/cexample/jni/Code6.cpp
|
a32ba2fb72596037d0e367af547a7f47a3711cdc
|
[] |
no_license
|
tsdl2013/wrapandroid-for-multilanguage
|
9f5407f489dc27691c9cdc3dea9adda74b80eb72
|
6bca0f018599d86a332963f68e5574d4f8e3d61c
|
refs/heads/master
| 2017-12-03T11:17:56.066124
| 2012-04-06T14:43:15
| 2012-04-06T14:43:15
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,366
|
cpp
|
Code6.cpp
|
#include "SRPWrapAndroidEngine_VSClass.h"
static class ClassOfSRPInterface *SRPInterface;
static void *StarActivity;
VS_BOOL StarCoreService_Init(class ClassOfStarCore *starcore)
{
class ClassOfBasicSRPInterface *BasicSRPInterface;
//--init star core
BasicSRPInterface = starcore ->GetBasicInterface();
SRPInterface = BasicSRPInterface ->GetSRPInterface(BasicSRPInterface->QueryActiveService(NULL),"","");
void *ActivityClass;
ActivityClass = SRPInterface -> GetObjectEx(NULL,"ActivityClass");
StarActivity = (void *)SRPInterface -> ScriptCall(ActivityClass,NULL,"getCurrent","()O");
SRPInterface -> Print("Get Main Activity = %s", SRPInterface -> GetName(StarActivity));
//--create AbsoluteLayout
void *MyLayout = SRPInterface->MallocObject(StarActivity,VSATTRINDEX_ACTIVITYCLASS_VIEWGROUPQUEUE,&VSOBJID_AbsoluteLayoutClass,0,NULL);
void *MyIntent = SRPInterface->MallocObjectL(&VSOBJID_IntentClass,0,NULL);
SRPInterface -> ScriptCall(MyIntent,NULL,"setAction","(s)","android.intent.action.VIEW");
SRPInterface -> ScriptCall(MyIntent,NULL,"setData","(s)","http://www.google.com");
SRPInterface -> ScriptCall(StarActivity,NULL,"startActivity","(o)",MyIntent);
return VS_TRUE;
}
void StarCoreService_Term(class ClassOfStarCore *starcore)
{
SRPInterface -> Release();
return;
}
|
5120a8f365a996892663b248df1eb5b76279ff0c
|
66d404e3b14505c350e53f093b47c129c7935417
|
/MyAssign/StarNetwork.h
|
f6e03ef53b6ace237f2121118a77a3852fe99370
|
[
"MIT"
] |
permissive
|
hkujy/VC
|
3bb6faa90a406fddb520cc51ec7337ae08ea21c6
|
54b79fac4ecf4ac225b54325d879a580a9b17be6
|
refs/heads/master
| 2023-01-01T07:05:31.348115
| 2020-10-26T09:40:24
| 2020-10-26T09:40:24
| 293,498,909
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 6,021
|
h
|
StarNetwork.h
|
#ifndef STAR_NETWORK
#define STAR_NETWORK
#include "UsedTypes.h"
#include <string>
#include <unordered_map>
//#include <tr1/unordered_map>
#include <limits>
#include <list>
class StarNode;
class StarLink;
/** \brief This class implements forward star graph representation.
\details For details see \cite Sheffi1985. */
class StarNetwork {
public:
StarNetwork(int nbNodes, int nbLinks, std::string &netName);
~StarNetwork();
/** Adds node \b node to the internal data structure.
\note Node is assumed to have out-going links that must be added
after node addition, using method
addLink(). This method might throw an error.
*/
void addNode(StarNode *node);
/** Adds link \b link to internal data structure. Links are associated with the last
added node. This method might throw an error.
*/
void addLink(StarLink *link);
/** This method must be called once after all links and nodes were added to the network.
It create internal indexes (all internal indexes follow the convention that it is a number
between 0 and number of nodes, or number of links for node and link indexes respectively)
for all nodes and sets them appropriately.
*/
void linkNodes();
/** @return name of the network.
*/
std::string getNetName() const;
/** @return total number of nodes in the network.
*/
int getNbNodes() const;
/** @return total number of links in the network.
*/
int getNbLinks() const;
/** @return pointer to the first node. It must be used together with getNextNode() method.
For example, the entire forward star network
can be iterated as follows:
@code for (StarNode* node = beginNode(); node != NULL; node = getNextNode()) {
for (StarLink* link = beginLink(); link != NULL; link = getNextLink()) {
//do something with link and/or node
}
} @endcode
\warning it is not safe to use this method in a nested loop when this method is
called more than once on the same object.
*/
StarNode* beginNode() const;
/** Starts iteration process beginning with a node specified in the input by
index \b index. It must be used together with getNextNode() method.
\warning it is not safe to use this method in a nested loop when this method is
called more than once on the same object.
*/
StarNode* beginNode(int index) const;
/** \warning it is not safe to use this method in a nested loop when this method is
called more than once on the same object.
*/
StarNode* getNextNode() const;
/** This method must be used together with getNextLink() method.
\warning it is not safe to use this method in a nested loop when this method is
called more than once on the same object.
*/
StarLink* beginLink() const;
/** \warning it is not safe to use this method in a nested loop when this method is
called more than once on the same object.
*/
StarLink* getNextLink() const;
/** This method is used in order to iterate through all links of the network.
It must be used together with getNextOnlyLink() method.
\warning it is not safe to use this method in a nested loop when this method is
called more than once on the same object.
*/
StarLink* beginOnlyLink() const;
/** \warning it is not safe to use this method in a nested loop when this method is
called more than once on the same object.
*/
StarLink* getNextOnlyLink() const;
/** @return a pointer to a link specified by index \b linkIndex.
*/
StarLink* getLink(int linkIndex) const;
/** @return a pointer of type StarNode* to a node specified by index \b index.
However, nodes of this type are created only if they have out-going links. That's why
only such node can be returned by this method. If another node is attempted to get by
using this method, then NULL is returned.
*/
StarNode* getNodeWithLinks(int index);
/** @return internal index of a node specified by its ID
\note Avoid calling this function as much as possible.
It has average case complexity: constant,
worst case complexity: linear in container size.
*/
int getNodeIndex(int id);
/** Prints network on screen.
*/
void print();
/** Writes link flows to file \b fileName in the following format:
nodeFrom nodeTo linkFlow travelTime
Default number of printed digits for linkFlow and travelTime is 16.
*/
void printToFile(const std::string& fileName, int precision = 16);
/** Loads link flows from file specified by \b fileName (link travel times are recalculated).
File format is: nodeFrom nodeTo linkFlow travelTime
\note Link flows must correspond to the created network object, i.e.
the one that was specified in file with parameters.
*/
void loadFromFile(const std::string& fileName);
/** Goes through all links and evaluates all link cost functions.
*/
void calculateLinkCosts();
/** @return node ID given its internal index.
Complexity is linear in the container size (total number of nodes).
*/
int findID(int index) const;
// *************//
// Add 13 Oct 2019 by Jy
void calculateTotalCost() const;
FPType getTotalCost() const { return TotalCost; }
private:
const std::string netName_;
const int nbNodes_;
const int nbLinks_;
std::vector<StarNode*> nodes_;
std::vector<StarLink*> links_;
std::vector<int> pointers_;
int size_;
int sizeLinks_;
mutable int curNode_;
mutable int curLink_;
mutable int curOnlyLink_;
//std::tr1::unordered_map<int, int> idMap_;
std::unordered_map<int, int> idMap_;
bool linkAdded_;
/** Creates table of mapping between node ID and node indexes.
*/
void createIndexes();
/** This method is used in loadFromFile(). It attempts to load link flow \b\ flow to
a link with nodes
\b nodeFrom and \b nodeTo. If such link does not exists false is returned.
*/
bool assignLinkFlow(int nodeFrom, int nodeTo, FPType flow);
//****************//
// add 13 Oct 2019 by Jy
mutable FPType TotalCost;
};
#endif
|
6a6b13cdae05090b21b358bf2997d95906c93cb2
|
e78395669282e78918a3d439b0cb05410a72c0e3
|
/easy/CLEANUP/main.cpp
|
71b3dfb675cc8a23f9dc2e76ba7c4add4da3afba
|
[] |
no_license
|
iamitshaw/codechef-practice-problem
|
a177d843674b89d054e075f66150cbc778a568a1
|
0bef2cfb89f7f1298fdb23bb91d4592c85fbb88f
|
refs/heads/master
| 2023-06-15T03:41:44.880192
| 2021-07-05T17:23:40
| 2021-07-05T17:23:40
| 383,216,845
| 2
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,944
|
cpp
|
main.cpp
|
#include <bits/stdc++.h>
void display_job(std::vector<int32_t>& vector) {
for (const auto& item: vector) {
std::cout << item << " ";
}
/* move cursor to next-line */
std::cout << "\n";
}
int32_t main(int32_t argc, char* argv[]) {
/* fast input-output */
std::ios_base::sync_with_stdio(false);
std::cin.tie(nullptr);
std::cout.tie(nullptr);
/* get test_case */
int32_t test_case;
std::cin >> test_case;
while (test_case--) {
/* get number_of_jobs */
int32_t number_of_jobs;
std::cin >> number_of_jobs;
/* get number_of_jobs that
* has been completed */
int32_t number_of_completed_jobs;
std::cin >> number_of_completed_jobs;
/* get completed_jobs */
std::priority_queue<int32_t> priorityQueue;
int32_t job_index;
for (int32_t i{0}; i < number_of_completed_jobs; i++) {
std::cin >> job_index;
/* using minimum_priority_queue */
priorityQueue.push(-job_index);
}
/* 0: chef's turn & 1: assistant's turn */
int32_t turn{0};
std::vector<int32_t> chef_job;
std::vector<int32_t> assistant_job;
for (int32_t i{1}; i <= number_of_jobs; i++) {
if (priorityQueue.empty() || -priorityQueue.top() != i) {
/* if i-th job hasn't been finished */
if (turn == 0) {
chef_job.push_back(i);
} else {
assistant_job.push_back(i);
}
/* change turn */
turn = 1 - turn;
} else {
/* if i-th job has been finished */
priorityQueue.pop();
}
}
/* print jobs-finished by chef */
display_job(chef_job);
/* print jobs-finished by assistant */
display_job(assistant_job);
}
return 0;
}
|
41b1dec0f83e7da8b025603cb015ff2c7beb89ce
|
5898d3bd9e4cb58043b40fa58961c7452182db08
|
/part3/ch17/17-6-3-2-maintain-invarient/src/maintain_invarient.cpp
|
865b106fe744c4dc6f04195efbc0aa2dfe47d120
|
[] |
no_license
|
sasaki-seiji/ProgrammingLanguageCPP4th
|
1e802f3cb15fc2ac51fa70403b95f52878223cff
|
2f686b385b485c27068328c6533926903b253687
|
refs/heads/master
| 2020-04-04T06:10:32.942026
| 2017-08-10T11:35:08
| 2017-08-10T11:35:08
| 53,772,682
| 2
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 797
|
cpp
|
maintain_invarient.cpp
|
/*
* maintain_invarient.cpp
*
* Created on: 2016/08/01
* Author: sasaki
*/
#include <vector>
#include <iostream>
using namespace std;
struct Z {
vector<int> elem;
int my_favorite;
int* largest;
};
// add util
ostream& operator<<(ostream& os, const vector<int>& v)
{
os << "[ ";
for (auto x : v)
os << x << ", ";
os << "]";
return os;
}
void print(const Z& z)
{
cout << ".elem: " << z.elem << " .my_favorite: " << z.my_favorite
<< " .largest: " << z.largest << '\n';
}
// add main
int main()
{
Z v0;
cout << "Z v0; "; print(v0);
Z val {{1,2,3},1,&val.elem[2]};
cout << "Z val {{1,2,3},1,&val.elem[2]}; "; print(val);
Z v2 = val;
cout << "Z v2 = val; "; print(v2);
Z v3 = move(val);
cout << "Z v3 = move(val); "; print(v3);
cout << "val: "; print(val);
}
|
7f26647c1f53bb09ed2c95575d34650aabfb4b85
|
c9d73a74f5256782d30f86fd574e4a5ac1769729
|
/src/main.cpp
|
fb9d905d6a26ef49cd796f024c49fb8e328e719e
|
[] |
no_license
|
SzJoakim93/Travis_sample
|
c453f3b54bb9eba3644b0824127d8070fdfe5c72
|
e1ca439821d4701b5085cec86295d1c081f30df0
|
refs/heads/master
| 2021-03-29T08:49:11.002597
| 2020-03-18T15:33:30
| 2020-03-18T15:33:30
| 247,938,605
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 329
|
cpp
|
main.cpp
|
#include <iostream>
#include "utils.h"
using std::cout;
using std::cin;
using std::endl;
int main()
{
int a;
cout << "Add number: " << endl;
cin >> a;
cout << "Square: " << square(a) << endl;
cout << "Cube: " << cube(a) << endl;
cout << (isPrime(a) ? "Prime" : "Not prime") << endl;
return 0;
}
|
ea01dafff8ddc94adb64d27aa84f3c92be976148
|
6f874ccb136d411c8ec7f4faf806a108ffc76837
|
/code/VCSamples/VC2008Samples/MFC/general/dlgcbr32/Mdlsmain.cpp
|
3dc5dc44722b6965d3b1c68285ecedd2d9caeb17
|
[
"MIT"
] |
permissive
|
JetAr/ZDoc
|
c0f97a8ad8fd1f6a40e687b886f6c25bb89b6435
|
e81a3adc354ec33345e9a3303f381dcb1b02c19d
|
refs/heads/master
| 2022-07-26T23:06:12.021611
| 2021-07-11T13:45:57
| 2021-07-11T13:45:57
| 33,112,803
| 8
| 8
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 17,818
|
cpp
|
Mdlsmain.cpp
|
// Dlgcbr32.cpp : Defines the class behaviors for CModelessMain.
//
// This is a part of the Microsoft Foundation Classes C++ library.
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// This source code is only intended as a supplement to the
// Microsoft Foundation Classes Reference and related
// electronic documentation provided with the library.
// See these sources for detailed information regarding the
// Microsoft Foundation Classes product.
#include "stdafx.h"
#include <afxpriv.h>
#include "mdlsmain.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
/////////////////////////////////////////////////////////////////////////////
// CModelessMain
IMPLEMENT_DYNAMIC(CModelessMain, CModelessDialog)
BEGIN_MESSAGE_MAP(CModelessMain, CModelessDialog)
//{{AFX_MSG_MAP(CModelessMain)
ON_WM_CLOSE()
ON_WM_PAINT()
ON_WM_ERASEBKGND()
ON_WM_QUERYDRAGICON()
ON_WM_ENTERIDLE()
ON_WM_INITMENUPOPUP()
ON_WM_MENUSELECT()
ON_MESSAGE(WM_SETMESSAGESTRING, OnSetMessageString)
ON_MESSAGE(WM_POPMESSAGESTRING, OnPopMessageString)
//}}AFX_MSG_MAP
ON_NOTIFY_EX_RANGE(TTN_NEEDTEXTW, 0, 0xFFFF, OnToolTipText)
ON_NOTIFY_EX_RANGE(TTN_NEEDTEXTA, 0, 0xFFFF, OnToolTipText)
// Standard View menu options
ON_COMMAND(ID_VIEW_STATUS_BAR, OnStatusBarCheck)
ON_COMMAND(ID_VIEW_TOOLBAR, OnToolBarCheck)
ON_UPDATE_COMMAND_UI(ID_VIEW_STATUS_BAR, OnUpdateStatusBarMenu)
ON_UPDATE_COMMAND_UI(ID_VIEW_TOOLBAR, OnUpdateToolBarMenu)
// Standard status bar mode indicators
ON_UPDATE_COMMAND_UI(ID_INDICATOR_CAPS, OnUpdateKeyIndicator)
ON_UPDATE_COMMAND_UI(ID_INDICATOR_NUM, OnUpdateKeyIndicator)
ON_UPDATE_COMMAND_UI(ID_INDICATOR_SCRL, OnUpdateKeyIndicator)
END_MESSAGE_MAP()
/////////////////////////////////////////////////////////////////////////////
// CModelessMain Construction/Destruction
CModelessMain::CModelessMain()
{
m_hIcon = NULL;
m_nIDTracking = 0;
m_nIDLastMessage = 0;
m_lpaIDStatusBar = NULL;
m_cIDStatusBar = 0;
m_lpaIDToolBar = NULL;
m_cIDToolBar = 0;
m_nIDBitmap = 0;
}
CModelessMain::~CModelessMain()
{
}
////////////////////////////////////////////////////////////////////////////
// CModelessMain::Create
// Create saves away information about the status bar and toolbar,
// loads the dialog icon, and creates the dialog window. It assumes
// the dialog icon has the same resource ID as the dialog template
// itself.
BOOL CModelessMain::Create(UINT nIDTemplate,
const UINT FAR* lpaIDStatus, int cIDStatus,
const UINT FAR* lpaIDToolbar, int cIDToolbar,
UINT nIDBitmap)
{
m_hIcon = AfxGetApp()->LoadIcon(nIDTemplate);
m_lpaIDStatusBar = lpaIDStatus;
m_cIDStatusBar = cIDStatus;
m_lpaIDToolBar = lpaIDToolbar;
m_cIDToolBar = cIDToolbar;
m_nIDBitmap = nIDBitmap;
return CModelessDialog::Create(nIDTemplate);
}
BOOL CModelessMain::Create(LPCTSTR lpszTemplateName,
const UINT FAR* lpaIDStatus, int cIDStatus,
const UINT FAR* lpaIDToolbar, int cIDToolbar,
UINT nIDBitmap)
{
ASSERT(lpszTemplateName != NULL);
m_hIcon = AfxGetApp()->LoadIcon(lpszTemplateName);
m_lpaIDStatusBar = lpaIDStatus;
m_cIDStatusBar = cIDStatus;
m_lpaIDToolBar = lpaIDToolbar;
m_cIDToolBar = cIDToolbar;
m_nIDBitmap = nIDBitmap;
return CModelessDialog::Create(lpszTemplateName);
}
/////////////////////////////////////////////////////////////////////////////
// CModelessMain::OnClose
// OnClose handles the WM_CLOSE message by posting a WM_QUIT message
// (so the app shuts down), after performing default processing to
// actually close the window.
void CModelessMain::OnClose()
{
CModelessDialog::OnClose();
PostQuitMessage(0);
}
/////////////////////////////////////////////////////////////////////////////
// CModelessMain::OnInitDialog
// OnInitDialog centers the dialog on the screen and creates the status
// and toolbars. To make sure the control bars don't overlap any
// dialog controls, the dialog's client area is expanded by the amount
// of space required for the control bars.
BOOL CModelessMain::OnInitDialog()
{
CModelessDialog::OnInitDialog();
// Create status bar at the bottom of the dialog window
if (m_statusBar.Create(this))
{
m_statusBar.SetIndicators(m_lpaIDStatusBar, m_cIDStatusBar);
OnSetMessageString(AFX_IDS_IDLEMESSAGE);
// Make a sunken or recessed border around the first pane
m_statusBar.SetPaneInfo(0, m_statusBar.GetItemID(0),
SBPS_STRETCH, NULL );
}
// Create toolbar at the top of the dialog window
if (m_toolBar.Create(this))
{
m_toolBar.LoadBitmap(m_nIDBitmap);
m_toolBar.SetButtons(m_lpaIDToolBar, m_cIDToolBar);
}
m_toolBar.SetBarStyle(m_toolBar.GetBarStyle() |
CBRS_TOOLTIPS | CBRS_FLYBY | CBRS_SIZE_DYNAMIC);
// We need to resize the dialog to make room for control bars.
// First, figure out how big the control bars are.
CRect rcClientStart;
CRect rcClientNow;
GetClientRect(rcClientStart);
RepositionBars(AFX_IDW_CONTROLBAR_FIRST, AFX_IDW_CONTROLBAR_LAST,
0, reposQuery, rcClientNow);
// Now move all the controls so they are in the same relative
// position within the remaining client area as they would be
// with no control bars.
CPoint ptOffset(rcClientNow.left - rcClientStart.left,
rcClientNow.top - rcClientStart.top);
CRect rcChild;
CWnd* pwndChild = GetWindow(GW_CHILD);
while (pwndChild)
{
pwndChild->GetWindowRect(rcChild);
ScreenToClient(rcChild);
rcChild.OffsetRect(ptOffset);
pwndChild->MoveWindow(rcChild, FALSE);
pwndChild = pwndChild->GetNextWindow();
}
// Adjust the dialog window dimensions
CRect rcWindow;
GetWindowRect(rcWindow);
rcWindow.right += rcClientStart.Width() - rcClientNow.Width();
rcWindow.bottom += rcClientStart.Height() - rcClientNow.Height();
MoveWindow(rcWindow, FALSE);
// And position the control bars
RepositionBars(AFX_IDW_CONTROLBAR_FIRST, AFX_IDW_CONTROLBAR_LAST, 0);
// Set the icon for this dialog. The framework does this automatically
// when the application's main window is not a dialog
SetIcon(m_hIcon, TRUE); // Set big icon
SetIcon(m_hIcon, FALSE); // Set small icon
// Finally, center the dialog on the screen
CenterWindow();
return TRUE;
}
/////////////////////////////////////////////////////////////////////////////
// CModelessMain::OnPaint
// CModelessMain::OnEraseBkgnd
// CModelessMain::OnQueryDragIcon
// These functions are used to display a custom icon for the dialog.
//
// These functions use a technique described in KB article Q87976
// to display a custom icon for our dialog window. We assume that
// the icon has been loaded into m_hIcon.
void CModelessMain::OnPaint()
{
CPaintDC dc(this);
if (IsIconic() && m_hIcon)
{
// Erase the icon background when placed over other app window
DefWindowProc(WM_ICONERASEBKGND, (WORD)dc.m_hDC, 0L);
// Center the icon
CRect rc;
GetClientRect(&rc);
rc.left = (rc.right - ::GetSystemMetrics(SM_CXICON))/2;
rc.top = (rc.bottom - ::GetSystemMetrics(SM_CYICON))/2;
// Draw the icon
dc.DrawIcon(rc.left, rc.top, m_hIcon);
}
}
BOOL CModelessMain::OnEraseBkgnd(CDC* pDC)
{
if (IsIconic() && m_hIcon)
return TRUE;
else
return CModelessDialog::OnEraseBkgnd(pDC);
}
HCURSOR CModelessMain::OnQueryDragIcon()
{
return (HCURSOR)m_hIcon;
}
/////////////////////////////////////////////////////////////////////////////
// CModelessMain::OnInitMenuPopup
// OnInitMenuPopup updates the state of items on a popup menu.
//
// This code is based on CFrameWnd::OnInitMenuPopup. We assume the
// application does not support context sensitive help.
void CModelessMain::OnInitMenuPopup(CMenu* pPopupMenu, UINT /*nIndex*/, BOOL bSysMenu)
{
if (!bSysMenu)
{
ENSURE(pPopupMenu != NULL);
// check the enabled state of various menu items
CCmdUI state;
state.m_pMenu = pPopupMenu;
ASSERT(state.m_pOther == NULL);
state.m_nIndexMax = pPopupMenu->GetMenuItemCount();
for (state.m_nIndex = 0; state.m_nIndex < state.m_nIndexMax;
state.m_nIndex++)
{
state.m_nID = pPopupMenu->GetMenuItemID(state.m_nIndex);
if (state.m_nID == 0)
continue; // menu separator or invalid cmd - ignore it
ASSERT(state.m_pOther == NULL);
ASSERT(state.m_pMenu != NULL);
if (state.m_nID == (UINT)-1)
{
// possibly a popup menu, route to first item of that popup
state.m_pSubMenu = pPopupMenu->GetSubMenu(state.m_nIndex);
if (state.m_pSubMenu == NULL ||
(state.m_nID = state.m_pSubMenu->GetMenuItemID(0)) == 0 ||
state.m_nID == (UINT)-1)
{
continue; // first item of popup can't be routed to
}
state.DoUpdate(this, FALSE); // popups are never auto disabled
}
else
{
// normal menu item
// Auto enable/disable if command is _not_ a system command
state.m_pSubMenu = NULL;
state.DoUpdate(this, state.m_nID < 0xF000);
}
}
}
}
/////////////////////////////////////////////////////////////////////////////
// CModelessMain::OnEnterIdle
// OnEnterIdle updates the status bar when there's nothing better to do.
// This code is based on CFrameWnd::OnEnterIdle.
void CModelessMain::OnEnterIdle(UINT nWhy, CWnd* /*pWho*/)
{
if (nWhy != MSGF_MENU || m_nIDTracking == m_nIDLastMessage)
return;
OnSetMessageString(m_nIDTracking);
ASSERT(m_nIDTracking == m_nIDLastMessage);
}
/////////////////////////////////////////////////////////////////////////////
// CModelessMain::OnMenuSelect
// OnMenuSelect updates the status bar message, based on the state
// of the dialog menu.
//
// This code is based on CFrameWnd::OnMenuSelect. We assume the
// application does not support context sensitive help.
void CModelessMain::OnMenuSelect(UINT nItemID, UINT nFlags, HMENU /*hSysMenu*/)
{
// set the tracking state
if (nFlags == 0xFFFF)
{
// cancel menu operation (go back to idle now)
m_nIDTracking = AFX_IDS_IDLEMESSAGE;
OnSetMessageString(m_nIDTracking); // set string now
ASSERT(m_nIDTracking == m_nIDLastMessage);
}
else if (nItemID == 0 ||
nFlags & (MF_SEPARATOR|MF_POPUP|MF_MENUBREAK|MF_MENUBARBREAK))
{
// nothing should be displayed
m_nIDTracking = 0;
}
else if (nItemID >= 0xF000 && nItemID < 0xF1F0)
{
// special string table entries for system commands
m_nIDTracking = ID_COMMAND_FROM_SC(nItemID);
ASSERT(m_nIDTracking >= AFX_IDS_SCFIRST &&
m_nIDTracking < AFX_IDS_SCFIRST + 31);
}
else
{
// track on idle
m_nIDTracking = nItemID;
}
}
/////////////////////////////////////////////////////////////////////////////
// CModelessMain::OnSetMessageString
// OnSetMessageString updates the status bar text.
//
// This code is based on CFrameWnd::OnSetMessageString. We assume
// a string ID is always passed in wParam.
LRESULT CModelessMain::OnSetMessageString(WPARAM wParam, LPARAM /*lParam*/)
{
UINT nIDMsg = (UINT)wParam;
CString strMsg;
if (nIDMsg)
{
if (strMsg.LoadString(nIDMsg) != 0)
{
CString strStatusText;
AfxExtractSubString(strStatusText, strMsg, 0, '\n');
m_statusBar.SetWindowText(strStatusText);
}
else
TRACE1("Warning: no message line prompt for ID %x%04X\n", nIDMsg);
}
UINT nIDLast = m_nIDLastMessage;
m_nIDLastMessage = nIDMsg;
m_nIDTracking = nIDMsg;
return nIDLast;
}
/////////////////////////////////////////////////////////////////////////////
// CModelessMain::OnStatusBarCheck
// OnStatusBarCheck toggles the status of the status bar when the
// corresponding View option is selected from the menu.
void CModelessMain::OnStatusBarCheck()
{
m_statusBar.ShowWindow(m_statusBar.IsWindowVisible() ? SW_HIDE : SW_SHOWNA);
}
/////////////////////////////////////////////////////////////////////////////
// CModelessMain::OnUpdateStatusBarMenu
// OnUpdateStatusBarMenu checks or unchecks the View option,
// depending on whether or not the status bar is visible.
void CModelessMain::OnUpdateStatusBarMenu(CCmdUI* pCmdUI)
{
ASSERT(pCmdUI->m_nID == ID_VIEW_STATUS_BAR);
pCmdUI->SetCheck(m_statusBar.IsWindowVisible());
}
/////////////////////////////////////////////////////////////////////////////
// CModelessMain::OnToolBarCheck
// OnToolBarCheck toggles the status of the toolbar when the
// corresponding View option is selected from the menu.
void CModelessMain::OnToolBarCheck()
{
m_toolBar.ShowWindow(m_toolBar.IsWindowVisible() ? SW_HIDE : SW_SHOWNA);
}
/////////////////////////////////////////////////////////////////////////////
// CModelessMain::OnUpdateToolBarMenu
// OnUpdateToolBarMenu checks or unchecks the View option,
// depending on whether or not the toolbar is visible.
void CModelessMain::OnUpdateToolBarMenu(CCmdUI* pCmdUI)
{
ASSERT(pCmdUI->m_nID == ID_VIEW_TOOLBAR);
pCmdUI->SetCheck(m_toolBar.IsWindowVisible());
}
/////////////////////////////////////////////////////////////////////////////
// CModelessMain::OnUpdateKeyIndicator
// OnUpdateKeyIndicator enables or disables one of the key indicators
// in a status bar. It recognizes the CAPS, NUM, and SCRL keys.
void CModelessMain::OnUpdateKeyIndicator(CCmdUI* pCmdUI)
{
UINT nVK;
switch (pCmdUI->m_nID)
{
case ID_INDICATOR_CAPS:
nVK = VK_CAPITAL;
break;
case ID_INDICATOR_NUM:
nVK = VK_NUMLOCK;
break;
case ID_INDICATOR_SCRL:
nVK = VK_SCROLL;
break;
default:
TRACE1("Warning: OnUpdateKeyIndicator - unknown indicator 0x%04X\n",
pCmdUI->m_nID);
pCmdUI->ContinueRouting();
return; // not for us
}
pCmdUI->Enable(::GetKeyState(nVK) & 1);
// enable static text based on toggled key state
ASSERT(pCmdUI->m_bEnableChanged);
}
/////////////////////////////////////////////////////////////////////////////
// CModelessMain::OnPopMessageString
// Resets status bar message string. This code is based on
// CFrameWnd::OnPopMessageString
LRESULT CModelessMain::OnPopMessageString(WPARAM wParam, LPARAM lParam)
{
if (m_nFlags & WF_NOPOPMSG)
return 0;
return SendMessage(WM_SETMESSAGESTRING, wParam, lParam);
}
/////////////////////////////////////////////////////////////////////////////
// CModelessMain::OnToolTipText
// Handles TTN_NEEDTEXT message to display tooltips for the toolbar.
// This code is based on CFrameWnd::OnToolTipText
BOOL CModelessMain::OnToolTipText(UINT, NMHDR* pNMHDR, LRESULT* pResult)
{
ASSERT(pNMHDR->code == TTN_NEEDTEXTA || pNMHDR->code == TTN_NEEDTEXTW);
// allow top level routing frame to handle the message
if (GetRoutingFrame() != NULL)
return FALSE;
// need to handle both ANSI and UNICODE versions of the message
TOOLTIPTEXTA* pTTTA = (TOOLTIPTEXTA*)pNMHDR;
TOOLTIPTEXTW* pTTTW = (TOOLTIPTEXTW*)pNMHDR;
TCHAR szFullText[256];
CString strTipText;
UINT_PTR nID = (UINT_PTR)pNMHDR->idFrom;
if (pNMHDR->code == TTN_NEEDTEXTA && (pTTTA->uFlags & TTF_IDISHWND) ||
pNMHDR->code == TTN_NEEDTEXTW && (pTTTW->uFlags & TTF_IDISHWND))
{
// idFrom is actually the HWND of the tool
nID = ((UINT_PTR)(WORD)::GetDlgCtrlID((HWND)nID));
}
if (nID != 0) // will be zero on a separator
{
AfxLoadString((UINT)nID, szFullText);
// this is the command id, not the button index
AfxExtractSubString(strTipText, szFullText, 1, '\n');
}
#ifndef _UNICODE
if (pNMHDR->code == TTN_NEEDTEXTA)
_tcsncpy_s(pTTTA->szText, (sizeof(pTTTA->szText)/sizeof(pTTTA->szText[0])),
strTipText, _TRUNCATE);
else
{
int n = MultiByteToWideChar(CP_ACP, 0, strTipText, -1, pTTTW->szText,
sizeof(pTTTW->szText)/sizeof(pTTTW->szText[0]));
if (n > 0)
pTTTW->szText[n-1] = 0;
}
#else
if (pNMHDR->code == TTN_NEEDTEXTA)
{
int n = WideCharToMultiByte(CP_ACP, 0, strTipText, -1,
pTTTA->szText, sizeof(pTTTA->szText)/sizeof(pTTTA->szText[0]),
NULL, NULL);
if (n > 0)
pTTTA->szText[n-1] = 0;
}
else
_tcsncpy_s(pTTTW->szText, (sizeof(pTTTW->szText)/sizeof(pTTTW->szText[0])),
strTipText, _TRUNCATE);
#endif
*pResult = 0;
// bring the tooltip window above other popup windows
::SetWindowPos(pNMHDR->hwndFrom, HWND_TOP, 0, 0, 0, 0,
SWP_NOACTIVATE|SWP_NOSIZE|SWP_NOMOVE);
return TRUE; // message was handled
}
|
9bc20a490a25f419bc0e64a7ba6f51abe9bf6a90
|
82646fb7fe40db6dcdf238548128f7b633de94c0
|
/nyoj/270.cpp
|
68cdd5e348c6214337fc3080ca9536c0b61fc7c6
|
[] |
no_license
|
jtahstu/iCode
|
a7873618fe98e502c1e0e2fd0769d71b3adac756
|
42d0899945dbc1bab98092d21a1d946137a1795e
|
refs/heads/master
| 2021-01-10T22:55:47.677615
| 2016-10-23T12:42:38
| 2016-10-23T12:42:38
| 70,316,051
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,528
|
cpp
|
270.cpp
|
/*数的分解
时间限制:1000 ms | 内存限制:65535 KB
难度:1
描述
你的任务是找到一个最小的正整数Q,使Q的各位数的乘积等于N。
输入
最多450组测试数据。数据以EOF结尾。
输入一个整数N(0 ≤ N ≤ 400)。
输出
输出Q,如果Q不存在则输出−1。
样例输入
10
5
样例输出
25
5
来源
ural
上传者
李文鑫*/
#include<stdio.h>
int main()
{
int n,i,k,t,s;
while(scanf("%d",&n)!=EOF)
{
for(i=1;; i++)
{
k=i;
s=1;
while(k)
{
t=k%10;
s=s*t;
k=k/10;
}
if(s==n)
{
printf("%d\n",i);
break;
}
if(i>599)
{
printf("-1\n");
break;
}
}
}
}
#include<iostream>//最优codes
#include<cstdio>
using namespace std;
int main()
{
int n;
while(scanf("%d",&n)!=EOF)
{
for(int i=1;; i++)
{
int k=1;
int s=i;
while(s)
{
k*=(s%10);
s/=10;
}
if(k==n)
{
cout<<i<<endl;
break;
}
if(i>5000)
{
cout<<"-1"<<endl;
break;
}
}
}
return 0;
}
|
72d9b48b96914bc7b236058783f81dc1c156ebb0
|
b5e2f65f372c471f0901d3f5c361e2e90dd14cf9
|
/Framework/MetroidGameContent/EN_Rocket_HUD.h
|
c30562df22a3cdb234a0bd28aec98fd4b0d69636
|
[] |
no_license
|
tonykhoapro/Metroid
|
e6f9089d3b0334126184749dc7e93ade07ed0dc8
|
569e497342f352fef9f4d8240d13c667b7079c76
|
refs/heads/master
| 2021-05-10T21:55:13.100817
| 2018-01-20T15:52:01
| 2018-01-20T15:52:01
| 118,242,865
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 284
|
h
|
EN_Rocket_HUD.h
|
#pragma once
#include "GameFramework\GameObject\GameObject.h"
class EN_Rocket_HUD : public GameObject
{
public:
EN_Rocket_HUD();
virtual ~EN_Rocket_HUD();
SpriteRenderer* sprite;
GameObject* mainCamera;
virtual void OnSpawn() override;
virtual void LateUpdate() override;
};
|
c5440e3d556948ffe550f595bd9436e296557ad5
|
0daf354eb397ed0fb8f0df8a2ccf184713e2adcf
|
/src/Model/Solid/Viscoelastic/Viscoelastic.cpp
|
2eb7cebd6a8f7d6c16b7211cfee9411e39ddeac0
|
[] |
no_license
|
drinkingpanda/alamo
|
344799354a6bdcb4ac03b3d47850a7671253056f
|
072845db493a2dba47e722fd09d142961b644cce
|
refs/heads/master
| 2020-06-27T19:42:05.763347
| 2019-07-03T18:42:48
| 2019-07-03T18:42:48
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,199
|
cpp
|
Viscoelastic.cpp
|
#include "Viscoelastic.H"
#include <iomanip>
namespace Model
{
namespace Solid
{
namespace Viscoelastic
{
std::ostream&
operator<< (std::ostream& os,
const Viscoelastic& b)
{
#if AMREX_SPACEDIM == 2
std::array<Set::Matrix,6> gradu, eps;
gradu[0] << 1,0, 0,0; eps[0] = 0.5*(gradu[0] + gradu[0].transpose());
gradu[1] << 0,0, 0,1; eps[1] = 0.5*(gradu[1] + gradu[1].transpose());
gradu[5] << 0,1, 0,0; eps[5] = 0.5*(gradu[5] + gradu[5].transpose());
for (int i = -1; i < 7; i++)
{
if (i==-1) os << "┌ ┐" << std::endl;
//else if (i==5) os << "└ ";
else if (i < 6)
{
os << "│ ";
for (int j = 0; j < 6; j++)
{
if ((i==0 || i==1 || i==5) &&
(j==0 || j==1 || j==5))
{
Set::Scalar comp = (eps[i].transpose() * b(eps[j])).trace();
os << std::setw(10) << (fabs(comp)>1E-10 ? comp : 0);
}
else
os << std::setw(10) << "-";
}
os << " │" << std::endl;
}
else os << "└ ┘" << std::endl;
}
#endif
#if AMREX_SPACEDIM == 3
std::array<Set::Matrix,6> gradu, eps;
gradu[0] << 1,0,0, 0,0,0, 0,0,0; eps[0] = 0.5*(gradu[0] + gradu[0].transpose());
gradu[1] << 0,0,0, 0,1,0, 0,0,0; eps[1] = 0.5*(gradu[1] + gradu[1].transpose());
gradu[2] << 0,0,0, 0,0,0, 0,0,1; eps[2] = 0.5*(gradu[2] + gradu[2].transpose());
gradu[3] << 0,0,0, 0,0,1, 0,0,0; eps[3] = 0.5*(gradu[3] + gradu[3].transpose());
gradu[4] << 0,0,1, 0,0,0, 0,0,0; eps[4] = 0.5*(gradu[4] + gradu[4].transpose());
gradu[5] << 0,1,0, 0,0,0, 0,0,0; eps[5] = 0.5*(gradu[5] + gradu[5].transpose());
for (int i = -1; i < 7; i++)
{
if (i==-1) os << "┌ ┐" << std::endl;
//else if (i==5) os << "└ ";
else if (i < 6)
{
os << "│ ";
for (int j = 0; j < 6; j++)
{
Set::Scalar comp = (eps[i].transpose() * b(eps[j])).trace();
os << std::setw(10) << (fabs(comp)>1E-10 ? comp : 0);
}
os << " │" << std::endl;
}
else os << "└ ┘" << std::endl;
}
#endif
return os;
}
}
}
}
|
fca029fcedce4ea927ab431673ecec892cb8be3c
|
834fcda1290b2df392268695e161f47173b91b87
|
/include/tudocomp/compressors/lcpcomp/compress/MaxHeapStrategy.hpp
|
d543af99dac675fee22b841f170eeb632d1e1b40
|
[
"Apache-2.0"
] |
permissive
|
tudocomp/tudocomp
|
775fb57c784e3b57d98425255ef576b3d6b365e7
|
b5512f85f6b3408fb88e19c08899ec4c2716c642
|
refs/heads/public
| 2022-09-22T11:56:07.044256
| 2020-04-15T08:49:38
| 2020-04-15T08:49:38
| 49,510,447
| 19
| 16
|
NOASSERTION
| 2021-12-10T09:38:42
| 2016-01-12T15:48:46
|
C++
|
UTF-8
|
C++
| false
| false
| 3,245
|
hpp
|
MaxHeapStrategy.hpp
|
#pragma once
#include <tudocomp/Algorithm.hpp>
#include <tudocomp/ds/TextDS.hpp>
#include <tudocomp/ds/ArrayMaxHeap.hpp>
#include <tudocomp/compressors/lzss/LZSSFactors.hpp>
#include <tudocomp_stat/StatPhase.hpp>
namespace tdc {
namespace lcpcomp {
/// Implements the original "Max LCP" selection strategy for LCPComp.
///
/// This strategy constructs a deque containing suffix array entries sorted
/// by their LCP length. The entry with the maximum LCP is selected and
/// overlapping suffices are removed from the deque.
///
/// This was the original naive approach in "Textkompression mithilfe von
/// Enhanced Suffix Arrays" (BA thesis, Patrick Dinklage, 2015).
class MaxHeapStrategy : public Algorithm {
public:
inline static Meta meta() {
Meta m("lcpcomp_comp", "heap");
return m;
}
inline static ds::dsflags_t textds_flags() {
return ds::SA | ds::ISA | ds::LCP;
}
using Algorithm::Algorithm; //import constructor
template<typename text_t>
inline void factorize(text_t& text,
const size_t threshold,
lzss::FactorBuffer& factors) {
// Construct SA, ISA and LCP
StatPhase::wrap("Construct text ds", [&]{
text.require(text_t::SA | text_t::ISA | text_t::LCP);
});
auto& sa = text.require_sa();
auto& isa = text.require_isa();
auto lcp = text.release_lcp();
auto heap = StatPhase::wrap("Construct MaxLCPHeap", [&]{
// Count relevant LCP entries
size_t heap_size = 0;
for(size_t i = 1; i < lcp.size(); i++) {
if(lcp[i] >= threshold) ++heap_size;
}
// Construct heap
ArrayMaxHeap<typename text_t::lcp_type::data_type> heap(lcp, lcp.size(), heap_size);
for(size_t i = 1; i < lcp.size(); i++) {
if(lcp[i] >= threshold) heap.insert(i);
}
StatPhase::log("entries", heap.size());
return heap;
});
//Factorize
StatPhase::wrap("Process MaxLCPHeap", [&]{
while(heap.size() > 0) {
//get suffix with longest LCP
size_t m = heap.get_max();
//generate factor
size_t fpos = sa[m];
size_t fsrc = sa[m-1];
size_t flen = lcp[m];
factors.emplace_back(fpos, fsrc, flen);
//remove overlapped entries
for(size_t k = 0; k < flen; k++) {
heap.remove(isa[fpos + k]);
}
//correct intersecting entries
for(size_t k = 0; k < flen && fpos > k; k++) {
size_t s = fpos - k - 1;
size_t i = isa[s];
if(heap.contains(i)) {
if(s + lcp[i] > fpos) {
size_t l = fpos - s;
if(l >= threshold) {
heap.decrease_key(i, l);
} else {
heap.remove(i);
}
}
}
}
}
});
}
};
}}
|
4d60fe4a6d50d4824de06421154052064c8fc66c
|
11321d8f3f8dcda67d90fb62dc8d52d969f31020
|
/EQSignal/main.cpp
|
e342a8ee8738744fab6602ba86323e1c4fbfd6c1
|
[
"MIT"
] |
permissive
|
jiayingqi/EQSignal
|
1558948ee7640b2c2fbd25bdb336a71ff3b9e0e3
|
ac04d71a5b011bc3feb66562d6dda0b4e7e4e67b
|
refs/heads/master
| 2022-03-30T08:59:24.815696
| 2020-01-24T03:33:59
| 2020-01-24T03:33:59
| 268,415,521
| 2
| 0
|
MIT
| 2020-06-01T03:24:26
| 2020-06-01T03:24:26
| null |
UTF-8
|
C++
| false
| false
| 694
|
cpp
|
main.cpp
|
#include "mainwindow.h"
#include <QApplication>
#include <QSplashScreen>
#include <QDesktopWidget>
#include <QTranslator>
#include <QString>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
QString qm("/trans.qm");
qm.prepend(QApplication::applicationDirPath());
QTranslator *trans = new QTranslator;
trans->load(qm);
a.installTranslator(trans);
QSplashScreen *splash = new QSplashScreen;
splash->setPixmap(QPixmap(":/MainWindow/splash.png"));
splash->show();
QFont font;
font.setFamily("Microsoft YaHei");
a.setFont(font);
MainWindow w;
w.move(320, 100);
w.show();
splash->finish(&w);
return a.exec();
}
|
d52d0915838e3c36c36c928397cc9fdcd2b84427
|
b0c18633942e6ded10eb67603bee00bb27b6901d
|
/05 Bit Manipulation/5.8-Draw-Line/draw_line.cpp
|
08ee942d6f27b472e1743ed780b68f4296eff01d
|
[] |
no_license
|
lazystring/ctci
|
b8a950046c2e46e14f8f95b7439568a1accb6a10
|
9601685efa0f09e60209c0ea7fe6b20a0d3bafe4
|
refs/heads/master
| 2022-03-24T06:49:58.913413
| 2019-12-10T08:26:07
| 2019-12-10T08:26:07
| 52,692,123
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 667
|
cpp
|
draw_line.cpp
|
#include <iostream>
#include <cstdint>
#include <vector>
typedef uint8_t ubyte;
void drawByte(ubyte& b, int i, int j) {
int mask = ((1 << i + 1) - 1) & ~((1 << j) - 1);
b |= mask;
}
void drawLine(std::vector<ubyte>& screen, int width, int x1, int x2, int y) {
int startByte = width*y + x1/8;
int endByte = width*y + x2/8;
int startBit = x1 % 8;
int endBit = x2 % 8;
drawByte(screen[startByte], startBit, 8); // Fill in starting byte
drawByte(screen[endByte], endBit, 8); // Fill in ending byte
/* Fill all the bytes inbetween */
for (int i = startByte+1; i < endByte - 1; ++i) {
drawByte(screen[i], 0, 8);
}
}
int main() {
return 0;
}
|
b9312550faaa4b0596c6866719bb691432823822
|
d99308722d63c38daf8697aac46e454db9004252
|
/triss/src/client/Connection.h
|
c8a4a415cb2df6b813ee361073aaecfef9d5925c
|
[] |
no_license
|
przemekpastuszka/Triss
|
5bf38011a328727c208dbb6183cf4e90fb2a6430
|
7087c71baaefbb1824f261267924a0c2d564a68a
|
refs/heads/master
| 2021-05-26T20:03:52.083043
| 2013-06-11T21:11:48
| 2013-06-11T21:11:48
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,491
|
h
|
Connection.h
|
/*
* Copyright 2012 Michał Rychlik
*/
#ifndef TRISS_SRC_CLIENT_CONNECTION_H_
#define TRISS_SRC_CLIENT_CONNECTION_H_
#include <boost/asio.hpp>
#include <boost/tuple/tuple.hpp>
#include <string>
#include <vector>
class Connection {
private:
Connection(const Connection& c);
boost::asio::io_service io_service;
boost::asio::ip::tcp::socket socket_;
enum {
header_length = 8
};
std::string outbound_header_;
std::string outbound_data_;
char inbound_header_[header_length];
std::vector<char> inbound_data_;
public:
Connection(const std::string& host, const std::string& port);
boost::asio::ip::tcp::socket& socket();
void handle_connect(
const boost::system::error_code& e,
boost::asio::ip::tcp::resolver::iterator endpoint_iterator
);
template <typename T, typename Handler> void async_write(const T& t,
Handler handler);
template <typename T, typename Handler> void async_read(T& t,
Handler handler);
template <typename T, typename Handler> void handle_read_header(
const boost::system::error_code& e, T& t, boost::tuple<Handler> handler
);
template <typename T, typename Handler> void handle_read_data(
const boost::system::error_code& e, T& t, boost::tuple<Handler> handler
);
void run_io_service();
};
#endif /* TRISS_SRC_CLIENT_CONNECTION_H_ */
|
f697e089350a5d69c5a49cdcbcaad24cb37874ea
|
5ad33c22eb4531f41a3aaff28fa2a256538a2aee
|
/googletest/test/gtest_repeat_test.cc
|
f67b7886e1a3cc262c0d295907d78d3889b6d5ee
|
[
"BSD-3-Clause"
] |
permissive
|
google/googletest
|
abe74c32dccf56afd140275ccaf1dd083e7b52e1
|
8a6feabf04bec8fb125e0df0ad1195c42350725f
|
refs/heads/main
| 2023-09-05T14:59:43.435465
| 2023-08-25T14:45:33
| 2023-08-25T14:46:02
| 39,840,932
| 33,962
| 12,824
|
BSD-3-Clause
| 2023-09-14T02:37:48
| 2015-07-28T15:07:53
|
C++
|
UTF-8
|
C++
| false
| false
| 7,698
|
cc
|
gtest_repeat_test.cc
|
// Copyright 2008, Google Inc.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// Tests the --gtest_repeat=number flag.
#include <stdlib.h>
#include <iostream>
#include "gtest/gtest.h"
#include "src/gtest-internal-inl.h"
namespace {
// We need this when we are testing Google Test itself and therefore
// cannot use Google Test assertions.
#define GTEST_CHECK_INT_EQ_(expected, actual) \
do { \
const int expected_val = (expected); \
const int actual_val = (actual); \
if (::testing::internal::IsTrue(expected_val != actual_val)) { \
::std::cout << "Value of: " #actual "\n" \
<< " Actual: " << actual_val << "\n" \
<< "Expected: " #expected "\n" \
<< "Which is: " << expected_val << "\n"; \
::testing::internal::posix::Abort(); \
} \
} while (::testing::internal::AlwaysFalse())
// Used for verifying that global environment set-up and tear-down are
// inside the --gtest_repeat loop.
int g_environment_set_up_count = 0;
int g_environment_tear_down_count = 0;
class MyEnvironment : public testing::Environment {
public:
MyEnvironment() = default;
void SetUp() override { g_environment_set_up_count++; }
void TearDown() override { g_environment_tear_down_count++; }
};
// A test that should fail.
int g_should_fail_count = 0;
TEST(FooTest, ShouldFail) {
g_should_fail_count++;
EXPECT_EQ(0, 1) << "Expected failure.";
}
// A test that should pass.
int g_should_pass_count = 0;
TEST(FooTest, ShouldPass) { g_should_pass_count++; }
// A test that contains a thread-safe death test and a fast death
// test. It should pass.
int g_death_test_count = 0;
TEST(BarDeathTest, ThreadSafeAndFast) {
g_death_test_count++;
GTEST_FLAG_SET(death_test_style, "threadsafe");
EXPECT_DEATH_IF_SUPPORTED(::testing::internal::posix::Abort(), "");
GTEST_FLAG_SET(death_test_style, "fast");
EXPECT_DEATH_IF_SUPPORTED(::testing::internal::posix::Abort(), "");
}
int g_param_test_count = 0;
const int kNumberOfParamTests = 10;
class MyParamTest : public testing::TestWithParam<int> {};
TEST_P(MyParamTest, ShouldPass) {
GTEST_CHECK_INT_EQ_(g_param_test_count % kNumberOfParamTests, GetParam());
g_param_test_count++;
}
INSTANTIATE_TEST_SUITE_P(MyParamSequence, MyParamTest,
testing::Range(0, kNumberOfParamTests));
// Resets the count for each test.
void ResetCounts() {
g_environment_set_up_count = 0;
g_environment_tear_down_count = 0;
g_should_fail_count = 0;
g_should_pass_count = 0;
g_death_test_count = 0;
g_param_test_count = 0;
}
// Checks that the count for each test is expected.
void CheckCounts(int expected) {
GTEST_CHECK_INT_EQ_(expected, g_environment_set_up_count);
GTEST_CHECK_INT_EQ_(expected, g_environment_tear_down_count);
GTEST_CHECK_INT_EQ_(expected, g_should_fail_count);
GTEST_CHECK_INT_EQ_(expected, g_should_pass_count);
GTEST_CHECK_INT_EQ_(expected, g_death_test_count);
GTEST_CHECK_INT_EQ_(expected * kNumberOfParamTests, g_param_test_count);
}
// Tests the behavior of Google Test when --gtest_repeat is not specified.
void TestRepeatUnspecified() {
ResetCounts();
GTEST_CHECK_INT_EQ_(1, RUN_ALL_TESTS());
CheckCounts(1);
}
// Tests the behavior of Google Test when --gtest_repeat has the given value.
void TestRepeat(int repeat) {
GTEST_FLAG_SET(repeat, repeat);
GTEST_FLAG_SET(recreate_environments_when_repeating, true);
ResetCounts();
GTEST_CHECK_INT_EQ_(repeat > 0 ? 1 : 0, RUN_ALL_TESTS());
CheckCounts(repeat);
}
// Tests using --gtest_repeat when --gtest_filter specifies an empty
// set of tests.
void TestRepeatWithEmptyFilter(int repeat) {
GTEST_FLAG_SET(repeat, repeat);
GTEST_FLAG_SET(recreate_environments_when_repeating, true);
GTEST_FLAG_SET(filter, "None");
ResetCounts();
GTEST_CHECK_INT_EQ_(0, RUN_ALL_TESTS());
CheckCounts(0);
}
// Tests using --gtest_repeat when --gtest_filter specifies a set of
// successful tests.
void TestRepeatWithFilterForSuccessfulTests(int repeat) {
GTEST_FLAG_SET(repeat, repeat);
GTEST_FLAG_SET(recreate_environments_when_repeating, true);
GTEST_FLAG_SET(filter, "*-*ShouldFail");
ResetCounts();
GTEST_CHECK_INT_EQ_(0, RUN_ALL_TESTS());
GTEST_CHECK_INT_EQ_(repeat, g_environment_set_up_count);
GTEST_CHECK_INT_EQ_(repeat, g_environment_tear_down_count);
GTEST_CHECK_INT_EQ_(0, g_should_fail_count);
GTEST_CHECK_INT_EQ_(repeat, g_should_pass_count);
GTEST_CHECK_INT_EQ_(repeat, g_death_test_count);
GTEST_CHECK_INT_EQ_(repeat * kNumberOfParamTests, g_param_test_count);
}
// Tests using --gtest_repeat when --gtest_filter specifies a set of
// failed tests.
void TestRepeatWithFilterForFailedTests(int repeat) {
GTEST_FLAG_SET(repeat, repeat);
GTEST_FLAG_SET(recreate_environments_when_repeating, true);
GTEST_FLAG_SET(filter, "*ShouldFail");
ResetCounts();
GTEST_CHECK_INT_EQ_(1, RUN_ALL_TESTS());
GTEST_CHECK_INT_EQ_(repeat, g_environment_set_up_count);
GTEST_CHECK_INT_EQ_(repeat, g_environment_tear_down_count);
GTEST_CHECK_INT_EQ_(repeat, g_should_fail_count);
GTEST_CHECK_INT_EQ_(0, g_should_pass_count);
GTEST_CHECK_INT_EQ_(0, g_death_test_count);
GTEST_CHECK_INT_EQ_(0, g_param_test_count);
}
} // namespace
int main(int argc, char **argv) {
testing::InitGoogleTest(&argc, argv);
testing::AddGlobalTestEnvironment(new MyEnvironment);
TestRepeatUnspecified();
TestRepeat(0);
TestRepeat(1);
TestRepeat(5);
TestRepeatWithEmptyFilter(2);
TestRepeatWithEmptyFilter(3);
TestRepeatWithFilterForSuccessfulTests(3);
TestRepeatWithFilterForFailedTests(4);
// It would be nice to verify that the tests indeed loop forever
// when GTEST_FLAG(repeat) is negative, but this test will be quite
// complicated to write. Since this flag is for interactive
// debugging only and doesn't affect the normal test result, such a
// test would be an overkill.
printf("PASS\n");
return 0;
}
|
e09e97ab725c9f77d9a9ad0fae97c33de14dd53d
|
99aaf505f9fae90731aba60fca223abaee228f68
|
/faq/leetcode/oj/swap_node_in_pairs.cpp
|
604410507ee77d490c75a7d1fa5c48e188b588f6
|
[] |
no_license
|
pamd/foo
|
13c3c354141b456f79274787aeb3e71c1f26e56b
|
52ce658f3adac4aa618706d1256ead26e90ab6fe
|
refs/heads/master
| 2016-09-05T14:35:22.727306
| 2015-12-27T22:42:58
| 2015-12-27T22:42:58
| 31,291,416
| 2
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,035
|
cpp
|
swap_node_in_pairs.cpp
|
/* Leetcode OJ: Given a linked list, swap every two adjacent nodes
* and return its head. For example, given 1->2->3->4, you should
* return the list as 2->1->4->3.
* Your algorithm should use only constant space. You may not modify
* the values in the list, only nodes itself can be changed.
*/
// Definition for singly-linked list.
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
// 16ms for large dataset
class Solution {
public:
ListNode* swapPairs(ListNode *head) {
// If the list has less than two nodes
if (!head || !head->next)
return head;
ListNode* ret = head->next;
ListNode* tail = 0;
while (head && head->next) {
ListNode* next = head->next;
ListNode* tmp = next->next;
next->next = head;
if (tail)
tail->next = next;
tail = head;
head = tmp;
}
// Tail must be a valid node, because the list has at least two nodes
tail->next = head;
return ret;
}
};
// Dropbox solution: use pointer to pointer,
// seems fancy, but harder to follow
//--------------------------------------------------------------------
void ReverseList(ListNode ** head, ListNode* tail) {
ListNode* p = *head;
ListNode* q = tail;
ListNode* n;
// Make 'next' pointer of node point to previous node
while( p != tail) {
n = p->next;
p->next = q;
q = p;
p = n;
}
// Make head pointer to new start
*head = q;
}
ListNode *SwapPairs(ListNode *head) {
ListNode ** h = &head;
ListNode * t = head;
ListNode * n = head;
while(1) {
int count = 2;
while(--count > 0 && t != NULL) {
t = t->next;
}
if (t == NULL)
break;
/* After reverse the list, the head node would be the last node,
* and pointer to the next segment, we need to reserve this node
* to find next start point. */
n = *h;
ReverseList(h, t->next);
// Begin next reverse
h = &n->next;
t= n->next;
}
return head;
}
|
def5c6ef66d7331739a9a38cb5e581867fb33eea
|
18b9c8e0b0bcfdc6a4eb7abc53ce1bbf2b400bc0
|
/Point.h
|
e2f6fc1f9b635d9df6a71f8a0a6a2cd3c7110258
|
[
"MIT"
] |
permissive
|
Garydos/conways-game-of-life-windows-cmd
|
0584e2d2ac8836db056fb061fa6423a979671f99
|
3bc568c9e52ea3915f2079ab1d8d2efd5abcbd2a
|
refs/heads/master
| 2020-04-20T08:32:22.378023
| 2019-02-01T18:53:40
| 2019-02-01T18:53:40
| 168,741,878
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 615
|
h
|
Point.h
|
#ifndef GUARD_POINT_H
#define GUARD_POINT_H
#include <iostream>
#include <string>
class Point {
private:
friend std::ostream& operator<<(std::ostream&, const Point&);
int x;
int y;
public:
Point() {}
Point(int x, int y) : x(x), y(y) {}
int getX() const;
int getY() const;
void setX(int);
void setY(int);
bool isNeighbor(const Point&) const;
bool operator<(const Point&) const;
bool operator==(const Point&) const;
//operator std::string();
};
std::ostream& operator<<(std::ostream&, const Point&);
#endif // GUARD_POINT_H
|
046ef2d4953208eb437fb24bff89c17d6c93d135
|
e6962eb67fead60da3df5b432a518b6efd85376d
|
/src/main.cpp
|
494eae7837cfe47b8df89298ec8bc6b6370b34b7
|
[] |
no_license
|
Trobolit/data_gather
|
2da8e7d6fc5891568a9501ffe6a7fcb9cb8e308c
|
d49c6d70da33da21f0b4e7d2a69b7af8a11cd948
|
refs/heads/master
| 2020-04-02T13:40:35.358153
| 2018-10-24T11:45:34
| 2018-10-24T11:45:34
| 154,491,473
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,833
|
cpp
|
main.cpp
|
#include "ros/ros.h"
#include "sensor_msgs/Joy.h"
#include "geometry_msgs/Twist.h"
#include <time.h>
#include <math.h>
#include "std_msgs/Float32MultiArray.h"
#include "std_msgs/MultiArrayLayout.h"
#include "std_msgs/MultiArrayDimension.h"
#include "std_msgs/Bool.h"
//constant setup variables change those values here
#define NODE_NAME "torque_step_sysid"
#define SUBSCRIBE_POWER "motor_power" //publishing channel
#define SUBSCRIBE_WHEEL_VEL "wheel_velocity"
#define BUFFER_SIZE 5
#define POWER_BUFFER_SIZE 200
#define LOOP_FREQ 20
geometry_msgs::Twist pwr_msg;
ros::Subscriber motor_power_sub;
ros::Subscriber wheel_vel_sub;
float current_L_vel = 0;
float current_R_vel = 0;
float current_L_pwr = 0;
float current_R_pwr = 0;
float t_elapsed = 0;
int loop_times = 0;
void encoderCallback(const std_msgs::Float32MultiArray::ConstPtr& array)
{
current_L_vel = array->data[0];
current_R_vel = array->data[1];
}
void motorPowerCallback(const geometry_msgs::Twist::ConstPtr & msg)
{
current_R_pwr = msg->linear.y;
current_L_pwr = msg->linear.x;
}
int main(int argc, char **argv)
{
ros::init(argc, argv, NODE_NAME);
ros::NodeHandle n;
ros::Rate loop_rate(LOOP_FREQ);
//set up communication channels
// TODO add the other channels
motor_power_sub = n.subscribe<geometry_msgs::Twist>(SUBSCRIBE_POWER, POWER_BUFFER_SIZE, motorPowerCallback);
wheel_vel_sub = n.subscribe<std_msgs::Float32MultiArray>(SUBSCRIBE_WHEEL_VEL, BUFFER_SIZE, encoderCallback);
float updatefreq = LOOP_FREQ;
ROS_INFO("Data in format: t, L_pow, R_pow, L_vel, R_vel");
while(ros::ok()){
t_elapsed = (float)loop_times/LOOP_FREQ ;
ROS_INFO("%f,%f,%f,%f,%f",t_elapsed, current_L_pwr, current_R_pwr, current_L_vel, current_R_vel);
loop_times++;
ros::spinOnce();
loop_rate.sleep();
}
return 0;
}
|
745293ff353e58cab533ac83020c8196a6686d94
|
6b2a8dd202fdce77c971c412717e305e1caaac51
|
/solutions_5630113748090880_0/C++/tobielf/B.cpp
|
1dd1cbbd5b4a056b069e6e9cb68bf1827880d95a
|
[] |
no_license
|
alexandraback/datacollection
|
0bc67a9ace00abbc843f4912562f3a064992e0e9
|
076a7bc7693f3abf07bfdbdac838cb4ef65ccfcf
|
refs/heads/master
| 2021-01-24T18:27:24.417992
| 2017-05-23T09:23:38
| 2017-05-23T09:23:38
| 84,313,442
| 2
| 4
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 558
|
cpp
|
B.cpp
|
#include <iostream>
#include <string>
using namespace std;
int main() {
int T;
int t;
int i, j;
int N;
int heights[2510];
int h;
freopen("B.in", "r", stdin);
freopen("B.out", "w", stdout);
cin >> T;
for (t = 1; t <= T; ++t) {
cin >> N;
memset(heights, 0, sizeof(heights));
for (i = 0; i < 2*N-1; ++i) {
for (j = 0; j < N; ++j) {
cin >> h;
heights[h]++;
}
}
// build grid
cout << "Case #" << t << ": ";
for (i = 1; i <= 2500; ++i) {
if (heights[i] % 2 != 0)
cout << i << " ";
}
cout << endl;
}
return 0;
}
|
18cb64109e29773c82868b570aa58f38fe5fe618
|
d0ae3ac5c9b8d5a70b006d030bd1ca3801cc4533
|
/HazelcastCppClient/Client/HazelcastClient.hpp
|
b73fa5f43c6fa0f70bef1d49b8c7fd03720ed37e
|
[] |
no_license
|
ismylhakkituran/HazelcastCppClient
|
ea34a07cfeadca784bbfabdcc306e662e98b8ca8
|
ae349b996b8d1f3993ed1022c8744737192979c3
|
refs/heads/master
| 2020-04-22T19:34:52.467036
| 2012-07-27T12:52:09
| 2012-07-27T12:52:09
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,338
|
hpp
|
HazelcastClient.hpp
|
// Definition of the ClientConfig class
#ifndef HazelcastClient_class
#define HazelcastClient_class
#include <vector>
#include "ClientConfig.hpp"
#include "../Connection/Connection.hpp"
using std::string;
class HazelcastClient // : private Socket
{
public:
HazelcastClient ( ClientConfig& clientconfig );
~HazelcastClient ( );
void auth (ClientConfig& clientconfig);
bool destroy (string flag,string type,string name);
bool trxbegin (string flag);
bool trxcommit (string flag);
bool trxrollback(string flag);
bool instances (string flag,std::vector<string>& type,std::vector<string>& instance ); // will be parse
bool members (string flag,std::vector<string>& members); // will be parse
bool clustertime(string flag,string& time);
bool ping (string flag);
bool partitions (string flag,string key,string& pid,string& adress); // will be parse
bool partitions (string flag,std::vector<string>& pid,std::vector<string>& adress); // will be parse
Connection connection;
private:
//Connection socket;
std::string endOfLine;
};
//---------------------------------------------------------------------------------------
//---------------------------------------------------------------------------------------
#endif
|
59a1b1b597d55a107f7a9843e5cdf581ea7fb046
|
803b666adae190848ce17c6c79f014b0cb28c757
|
/2.std::vector/vector.cpp
|
c3f9773d2394ed9e4dd715295424a3b306d9f631
|
[] |
no_license
|
raj5036/CPP-STLs
|
9e2a22a5dae75996e28402f02e8d03458bec81fc
|
46a6889d002240c0c832a4b1ac030e4a2195dae0
|
refs/heads/master
| 2022-12-07T07:45:20.541061
| 2020-08-18T12:29:24
| 2020-08-18T12:29:24
| 282,259,759
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 927
|
cpp
|
vector.cpp
|
#include<bits/stdc++.h>
#include<vector>
using namespace std;
int main(){
vector<int> v;
//To reserve a specific size of the vector so that the system doesn't go through a lot of workload which causes due to dynamic resizing of the vector.It saves time
v.reserve(10);
for(int i=1;i<=10;i++)
v.push_back(i);
for(int i=0;i<v.size();i++)
cout<<v.at(i)<<" ";
cout<<endl;
cout<<"Size "<<v.size()<<endl;
cout<<"Capacity "<<v.capacity()<<endl;
v.shrink_to_fit();
cout<<"Capacity after shrinking(shrink_to_fit) "<<v.capacity()<<endl;
cout<<"front "<<v.front()<<endl;
cout<<"Back "<<v.back()<<endl;
v.pop_back(); // removes last element
vector<int> myvector={ 1, 2, 3, 4, 5 };
vector<int>::iterator it;
it = myvector.begin();
myvector.erase(it);
// Printing the Vector
for (auto it = myvector.begin(); it != myvector.end(); ++it)
cout << ' ' << *it;
return 0;
}
|
5961cafbcc24c252d2c14c6d7f3c8e75a3b9d068
|
a5a1a876cb0811420b327456b3111702aee19012
|
/WTL/io/Console.hpp
|
53f3beec2deb698163809af114589e103c8ca76a
|
[] |
no_license
|
CyberSys/Win32-Template-Library
|
ab2f761bad0c19058bcadd50c00b31b495847480
|
d53b1ad90b9414944f25179130d467edb29ad75d
|
refs/heads/master
| 2022-02-15T12:45:32.005469
| 2016-02-28T22:02:39
| 2016-02-28T22:02:39
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 34,001
|
hpp
|
Console.hpp
|
/////////////////////////////////////////////////////////////////////////////////////////
//! \file wtl\io\Console.hpp
//! \brief Contains the buffer, manipulators, traits, and stream type for a custom output stream
//! \brief that supports writing formatted coloured text to stdout through the Win32 console API
//! \brief using the existing stream manipulators provided by the standard library.
//! \date 28 November 2015
//! \author Nick Crowley
//! \copyright Nick Crowley. All rights reserved.
/////////////////////////////////////////////////////////////////////////////////////////
#ifndef WTL_CONSOLE_HPP
#define WTL_CONSOLE_HPP
#include <string> //!< std::char_traits
#include <vector> //!< std::vector
#include <deque> //!< std::deque
#include <sstream> //!< std::basic_stringstream
#include <ios> //!< std::ios_base
#include <WTL/utils/Point.hpp> //!< Point
#include <WTL/utils/exception.hpp> //!< caught-exception
//////////////////////////////////////////////////////////////////////////////////////////
//! \namespace wtl - Windows template library
//////////////////////////////////////////////////////////////////////////////////////////
namespace wtl
{
//////////////////////////////////////////////////////////////////////////////////////////
//! \struct console_traits - Traits type for the debug-console stream providing a custom stream position type
//!
//! \tparam CHAR - Character type
//////////////////////////////////////////////////////////////////////////////////////////
template <typename CHAR>
struct console_traits : std::char_traits<CHAR>
{
//////////////////////////////////////////////////////////////////////////////////////////
//! \struct Coord - Custom stream position type
//////////////////////////////////////////////////////////////////////////////////////////
struct Coord : Point<int16_t>
{
// ---------------------------------- TYPES & CONSTANTS ---------------------------------
//! \alias type - Define own type
using type = Coord;
//! \alias base - Define base type
using base = Point<int16_t>;
// ----------------------------------- REPRESENTATION -----------------------------------
// ------------------------------------ CONSTRUCTION ------------------------------------
//////////////////////////////////////////////////////////////////////////////////////////
// Coord::Coord
//! Construct from co-ordinates
//////////////////////////////////////////////////////////////////////////////////////////
using base::Point;
//////////////////////////////////////////////////////////////////////////////////////////
// Coord::Coord
//! Construct from base type co-ordinates
//!
//! \param[in] const& pt - Co-ordinates
//////////////////////////////////////////////////////////////////////////////////////////
template <typename T>
Coord(const Point<T>& pt) : base(pt)
{}
//////////////////////////////////////////////////////////////////////////////////////////
// Coord::Coord
//! Dummy constructor for constructing invalid position sentinel value (for compatibilty with basic_streambuf stub methods)
//!
//! \param[in] const& - Ignored
//////////////////////////////////////////////////////////////////////////////////////////
Coord(int) : base(-1,-1)
{}
//////////////////////////////////////////////////////////////////////////////////////////
// Coord::Coord
//! Dummy constructor for constructing invalid position sentinel value (for compatibilty with basic_streambuf stub methods)
//!
//! \param[in] const& - Ignored
//////////////////////////////////////////////////////////////////////////////////////////
template <typename T>
Coord(const std::fpos<T>&) : base(-1,-1)
{}
// ---------------------------------- ACCESSOR METHODS ----------------------------------
//////////////////////////////////////////////////////////////////////////////////////////
// Coord::operator== const
//! Compare against other points
//////////////////////////////////////////////////////////////////////////////////////////
using base::operator==;
//////////////////////////////////////////////////////////////////////////////////////////
// Coord::operator== const
//! Compare whether equal with invalid position sentinel value (-1)
//!
//! \param[in] const& - Ignored
//////////////////////////////////////////////////////////////////////////////////////////
bool operator==(const std::streamoff&) const
{
return *this == type(-1,-1);
}
// ----------------------------------- MUTATOR METHODS ----------------------------------
};
//! \alias pos_type - Define absolute stream position type as screen co-ordinate
using pos_type = Coord;
//! \alias off_type - Define relative stream offset type as position type
using off_type = pos_type;
};
//////////////////////////////////////////////////////////////////////////////////////////
//! \struct console_streambuf - Custom debug-console stream buffer
//!
//! \tparam CHAR - Character type
//! \tparam TRAITS - [optional] Type providing character traits
//!
//! \remarks Provides a custom stream buffer for the debug-console stream, enabling buffered output,
//! \remarks custom positioning, and handling of foreground/background colour attributes
//////////////////////////////////////////////////////////////////////////////////////////
template <typename CHAR, typename TRAITS = console_traits<CHAR>>
struct console_streambuf : std::basic_streambuf<CHAR,TRAITS>
{
// ---------------------------------- TYPES & CONSTANTS ---------------------------------
//! \alias type - Define own type
using type = console_streambuf<CHAR,TRAITS>;
//! \alias base - Define base type
using base = std::basic_streambuf<CHAR,TRAITS>;
//! \alias char_type - Inherit character type
using char_type = typename base::char_type;
//! \alias int_type - Inherit integer representation type
using int_type = typename base::int_type;
//! \alias openmode - Inherit stream open mode
using openmode = std::ios_base::openmode;
//! \alias off_type - Inherit offset type
using off_type = typename base::off_type;
//! \alias pos_type - Inherit position type
using pos_type = typename base::pos_type;
//! \alias seekdir - Inherit seek direction
using seekdir = std::ios_base::seekdir;
//! \alias traits_type - Inherit traits type
using traits_type = typename base::traits_type;
private:
static const uint16_t BackgroundMask = 0x00f0, //!< Background text attributes mask
ForegroundMask = 0x000f; //!< Foreground text attributes mask
// ----------------------------------- REPRESENTATION -----------------------------------
private:
std::vector<char_type> Buffer; //!< Buffer 'put area'
::HANDLE Handle; //!< console_stream handle
std::deque<uint16_t> Stack; //!< Formatting stack
// ------------------------------------ CONSTRUCTION ------------------------------------
public:
//////////////////////////////////////////////////////////////////////////////////////////
// console_streambuf::console_streambuf
//! Construct debug-console buffer
//!
//! \param[in] len - [optional] Length of buffer (in characters)
//!
//! \throw std::runtime_error - Unable to retrieve handle to stdout
//////////////////////////////////////////////////////////////////////////////////////////
console_streambuf(uint32_t len = 1024) : Buffer(len), Handle(::GetStdHandle(STD_OUTPUT_HANDLE))
{
// Verify handle to stdout
if (!Handle || Handle == INVALID_HANDLE_VALUE)
throw std::runtime_error("Unable to get handle to stdout");
// Define put area
this->setp(Buffer.data(), Buffer.data() + Buffer.capacity());
}
// -------------------------------- COPY, MOVE & DESTROY --------------------------------
console_streambuf(const console_streambuf&) = default; //!< Copying produces a deep copy [Handle is not unique]
console_streambuf(console_streambuf&&) = default; //!< Can be moved
//////////////////////////////////////////////////////////////////////////////////////////
// console_streambuf::~console_streambuf
//! Flushes the buffer
//////////////////////////////////////////////////////////////////////////////////////////
~console_streambuf() override
{
sync();
}
// ----------------------------------- STATIC METHODS -----------------------------------
// ---------------------------------- ACCESSOR METHODS ----------------------------------
private:
//////////////////////////////////////////////////////////////////////////////////////////
// console_streambuf::used const
//! Query the number of characters written to the 'put area'
//!
//! \return uint32_t - Number of characters in the 'put area'
//////////////////////////////////////////////////////////////////////////////////////////
uint32_t used() const
{
return static_cast<uint32_t>(this->pptr() - this->pbase());
}
// ----------------------------------- MUTATOR METHODS ----------------------------------
public:
//////////////////////////////////////////////////////////////////////////////////////////
// console_streambuf::push
//! Saves the current formatting to the stack. (Also flushes the output)
//////////////////////////////////////////////////////////////////////////////////////////
void push()
{
::CONSOLE_SCREEN_BUFFER_INFO sb;
//! Flush 'put area' to output stream
sync();
//! Save the current attributes
::GetConsoleScreenBufferInfo(Handle, &sb);
Stack.push_back(sb.wAttributes);
}
//////////////////////////////////////////////////////////////////////////////////////////
// console_streambuf::pop
//! Restores formatting previously saved to the stack. (Also flushes the output)
//////////////////////////////////////////////////////////////////////////////////////////
void pop()
{
// Do nothing if empty
if (!Stack.empty())
{
//! Flush 'put area' to output stream
sync();
//! Replace current formatting with that saved on the stack
::SetConsoleTextAttribute(Handle, Stack.front());
Stack.pop_front();
}
}
//////////////////////////////////////////////////////////////////////////////////////////
// console_streambuf::setback
//! Modifies the background colour
//!
//! \param[in] flag - Foreground colour
//////////////////////////////////////////////////////////////////////////////////////////
void setback(uint16_t flag)
{
::CONSOLE_SCREEN_BUFFER_INFO sb;
//! Flush 'put area' to output stream
sync();
// Preserve foreground formatting, change background formatting
::GetConsoleScreenBufferInfo(Handle, &sb);
::SetConsoleTextAttribute(Handle, (sb.wAttributes & ForegroundMask) | (flag & BackgroundMask));
}
//////////////////////////////////////////////////////////////////////////////////////////
// console_streambuf::setfore
//! Modifies the foreground/text colour
//!
//! \param[in] flag - Foreground colour
//////////////////////////////////////////////////////////////////////////////////////////
void setfore(uint16_t flag)
{
::CONSOLE_SCREEN_BUFFER_INFO sb;
//! Flush 'put area' to output stream
sync();
// Preserve background formatting, change foreground formatting
::GetConsoleScreenBufferInfo(Handle, &sb);
::SetConsoleTextAttribute(Handle, (sb.wAttributes & BackgroundMask) | (flag & ForegroundMask));
}
protected:
//////////////////////////////////////////////////////////////////////////////////////////
// console_streambuf::overflow
//! Synchronizes the buffer and output sequence before writing another character
//!
//! \param[in] ch - Character to write
//! \return int_type - EOF if unsuccessful
//////////////////////////////////////////////////////////////////////////////////////////
int_type overflow(int_type ch = traits_type::eof()) override
{
//! Commit put area to the output stream
if (!flush())
{
//! [FAILED] Destroy put area
this->setp(nullptr, nullptr);
return traits_type::eof();
}
//! [~EOF] Store character in the put area
if (!traits_type::eq_int_type(ch, traits_type::eof()))
{
*this->pptr() = traits_type::to_char_type(ch);
this->pbump(1);
}
return ch;
}
//////////////////////////////////////////////////////////////////////////////////////////
// console_streambuf::seekpos
//! Seeks the get-pointer and/or put-pointer to a relative position
//!
//! \param[in] offset - Relative position
//! \param[in] origin - Seek origin
//! \param[in] mode - [optional] Whether to seek the get and/or put position
//! \return pos_type - New absolute position
//////////////////////////////////////////////////////////////////////////////////////////
pos_type seekoff(off_type offset, seekdir origin, openmode mode = std::ios_base::in | std::ios_base::out) override
{
::CONSOLE_SCREEN_BUFFER_INFO sb;
// Flush existing buffer
sync();
// Query current position
::GetConsoleScreenBufferInfo(Handle, &sb);
pos_type target = pos_type(sb.dwCursorPosition) + offset;
// Attempt to set new position
if (!::SetConsoleCursorPosition(Handle, target))
// [FAILED] Return existing position
return {sb.dwCursorPosition};
// Return new position
return target;
}
//////////////////////////////////////////////////////////////////////////////////////////
// console_streambuf::seekpos
//! Seeks the get-pointer and/or put-pointer to an absolute position
//!
//! \param[in] pos - Absolute position
//! \param[in] mode - [optional] Whether to seek the get and/or put position
//! \return pos_type - New absolute position
//////////////////////////////////////////////////////////////////////////////////////////
pos_type seekpos(pos_type pos, openmode mode = std::ios_base::in | std::ios_base::out) override
{
// Flush existing buffer
sync();
// Attempt to set new position
if (!::SetConsoleCursorPosition(Handle, pos))
{
::CONSOLE_SCREEN_BUFFER_INFO sb;
// [FAILED] Return existing position
::GetConsoleScreenBufferInfo(Handle, &sb);
return {sb.dwCursorPosition};
}
// Return new position
return pos;
}
//////////////////////////////////////////////////////////////////////////////////////////
// console_streambuf::sync
//! Synchronizes the buffer and output sequence
//!
//! \return int - 0 if successful, -1 otherwise
//////////////////////////////////////////////////////////////////////////////////////////
int sync() override
{
return !used() || flush() ? 0 : -1;
}
private:
//////////////////////////////////////////////////////////////////////////////////////////
// console_streambuf::flush
//! Flushes the buffer to the console
//!
//! \return bool - True iff successfully flushed buffer to output sequence
//////////////////////////////////////////////////////////////////////////////////////////
bool flush()
{
DWORD out = 0;
uint32_t len = used();
//! Commit put area to the output stream
if (!::WriteConsoleA(Handle, this->pbase(), len, &out, nullptr) || out != len)
{
//! [FAILED] Destroy put area
this->setp(nullptr, nullptr);
return false;
}
//! Update put pointer
this->pbump(0 - len);
return true;
}
};
//////////////////////////////////////////////////////////////////////////////////////////
//! \struct console_stream - Debug-console output stream
//!
//! \tparam CHAR - Character type
//! \tparam TRAITS - [optional] Character traits provider type
//////////////////////////////////////////////////////////////////////////////////////////
template <typename CHAR, typename TRAITS = console_traits<CHAR>>
struct console_stream : std::basic_ostream<CHAR,TRAITS>
{
// ---------------------------------- TYPES & CONSTANTS ---------------------------------
//! \alias type - Define own type
using type = console_stream<CHAR,TRAITS>;
//! \alias base - Define base type
using base = std::basic_ostream<CHAR,TRAITS>;
//! \var ident - Index of user-defined formatting flag used as magic number
static const int Ident;
// ----------------------------------- REPRESENTATION -----------------------------------
private:
console_streambuf<CHAR,TRAITS> Buffer; //!< Stream buffer
// ------------------------------------ CONSTRUCTION ------------------------------------
public:
//////////////////////////////////////////////////////////////////////////////////////////
// console_stream::console_stream
//! Constructs the debug console
//!
//! \throw std::runtime_error - Unable to retrieve handle to stdout
//////////////////////////////////////////////////////////////////////////////////////////
console_stream() : base(&Buffer)
{
// Set user-defined formatting flag that identifies stream as a debug-console
this->iword(Ident) = true;
}
// -------------------------------- COPY, MOVE & DESTROY --------------------------------
console_stream(const console_stream&) = default; //!< Can be copied
console_stream(console_stream&&) = default; //!< Can be moved
~console_stream() override = default; //!< Can be polymorphic
// ----------------------------------- STATIC METHODS -----------------------------------
//////////////////////////////////////////////////////////////////////////////////////////
// ::operator<< friend
//! Output overload for writing strings with different character traits
//!
//! \param[in,out] &os - Output stream
//! \param[in] const& str - String
//! \return base& - Reference to 'os'
//////////////////////////////////////////////////////////////////////////////////////////
/*template <typename STR_TRAITS, typename ALLOC>
friend base& operator<<(base& os, const std::basic_string<CHAR,STR_TRAITS,ALLOC>& str)
{
return os.write(str.data(), str.size());
}*/
// ---------------------------------- ACCESSOR METHODS ----------------------------------
// ----------------------------------- MUTATOR METHODS ----------------------------------
public:
//////////////////////////////////////////////////////////////////////////////////////////
// console_stream::push
//! Saves the current formatting to the stack
//////////////////////////////////////////////////////////////////////////////////////////
void push()
{
Buffer.push();
}
//////////////////////////////////////////////////////////////////////////////////////////
// console_stream::pop
//! Restores formatting previously saved to the stack
//////////////////////////////////////////////////////////////////////////////////////////
void pop()
{
Buffer.pop();
}
//////////////////////////////////////////////////////////////////////////////////////////
// console_stream::setback
//! Modifies the background colour
//!
//! \param[in] flag - Background colour
//////////////////////////////////////////////////////////////////////////////////////////
void setback(uint16_t flag)
{
Buffer.setback(flag);
}
//////////////////////////////////////////////////////////////////////////////////////////
// console_stream::setfore
//! Modifies the foreground/text colour
//!
//! \param[in] flag - Foreground colour
//////////////////////////////////////////////////////////////////////////////////////////
void setfore(uint16_t flag)
{
Buffer.setfore(flag);
}
};
//////////////////////////////////////////////////////////////////////////////////////////
//! \var console_stream::ident - Index of user-defined formatting flag used by debug-console streams
//////////////////////////////////////////////////////////////////////////////////////////
template <typename CHAR, typename TRAITS>
const int console_stream<CHAR,TRAITS>::Ident = std::ios_base::xalloc();
//////////////////////////////////////////////////////////////////////////////////////////
//! \alias console - Narrow-character debug-console stream
//////////////////////////////////////////////////////////////////////////////////////////
using console = console_stream<char>;
//////////////////////////////////////////////////////////////////////////////////////////
//! \alias console - Narrow-character debug-console stream
//////////////////////////////////////////////////////////////////////////////////////////
using wconsole = console_stream<wchar_t>;
//////////////////////////////////////////////////////////////////////////////////////////
//! \var wtl::cdebug - Narrow character debug console stream
//////////////////////////////////////////////////////////////////////////////////////////
extern console cdebug;
//////////////////////////////////////////////////////////////////////////////////////////
//! \struct textcol - Debug-console stream foreground colour manipulator
//////////////////////////////////////////////////////////////////////////////////////////
struct textcol
{
//! \enum colour_t - Foreground colours
enum colour_t : uint16_t
{
bold = FOREGROUND_INTENSITY, //!< Set bold text
black = 0, //!< Set black text
cyan = FOREGROUND_BLUE|FOREGROUND_GREEN, //!< Set cyan text
blue = FOREGROUND_BLUE, //!< Set blue text
green = FOREGROUND_GREEN, //!< Set green text
grey = bold, //!< Set grey text
purple = FOREGROUND_RED|FOREGROUND_BLUE, //!< Set purple text
red = FOREGROUND_RED, //!< Set red text
yellow = FOREGROUND_RED|FOREGROUND_GREEN, //!< Set yellow text
white = FOREGROUND_RED|FOREGROUND_GREEN|FOREGROUND_BLUE, //!< Set white text
};
//////////////////////////////////////////////////////////////////////////////////////////
// ::operator| friend
//! Performs foreground colours to be combined with bitwise OR
//////////////////////////////////////////////////////////////////////////////////////////
friend colour_t operator| (const colour_t& a, const colour_t& b)
{
return static_cast<colour_t>(static_cast<uint16_t>(a) | static_cast<uint16_t>(b));
}
//////////////////////////////////////////////////////////////////////////////////////////
// ::operator<< friend
//! Modifies the foreground/text colour of a debug-console stream
//!
//! \param[in,out] &s - Debug-console stream
//! \param[in] m - Foreground colour
//! \return std::basic_ostream<CHAR,TRAITS> - Reference to 's'
//////////////////////////////////////////////////////////////////////////////////////////
template <typename CHAR, typename TRAITS>
friend std::basic_ostream<CHAR,TRAITS>& operator<< (std::basic_ostream<CHAR,TRAITS>& s, colour_t m)
{
// Ensure stream is a debug-console then apply foreground formatting
if (s.iword(console_stream<CHAR,TRAITS>::Ident))
static_cast<console_stream<CHAR,TRAITS>&>(s).setfore(m);
return s;
}
};
//////////////////////////////////////////////////////////////////////////////////////////
//! \struct backcol - Debug-console stream background colour manipulator
//////////////////////////////////////////////////////////////////////////////////////////
struct backcol
{
//! \enum colour_t - Background colours
enum colour_t : uint16_t
{
bold = BACKGROUND_INTENSITY, //!< Set bold background
black = 0, //!< Set black background
cyan = BACKGROUND_BLUE|BACKGROUND_GREEN, //!< Set cyan background
blue = BACKGROUND_BLUE, //!< Set blue background
green = BACKGROUND_GREEN, //!< Set green background
grey = bold, //!< Set grey background
purple = BACKGROUND_RED|BACKGROUND_BLUE, //!< Set purple background
red = BACKGROUND_RED, //!< Set red background
yellow = BACKGROUND_RED|BACKGROUND_GREEN, //!< Set yellow background
white = BACKGROUND_RED|BACKGROUND_GREEN|BACKGROUND_BLUE, //!< Set white background
};
//////////////////////////////////////////////////////////////////////////////////////////
// ::operator| friend
//! Performs background colours to be combined with bitwise OR
//////////////////////////////////////////////////////////////////////////////////////////
friend colour_t operator| (const colour_t& a, const colour_t& b)
{
return static_cast<colour_t>(static_cast<uint16_t>(a) | static_cast<uint16_t>(b));
}
//////////////////////////////////////////////////////////////////////////////////////////
// ::operator<< friend
//! Modifies the background colour of a debug-console stream
//!
//! \param[in,out] &s - Debug-console stream
//! \param[in] m - Background colour
//! \return std::basic_ostream<CHAR,TRAITS> - Reference to 's'
//////////////////////////////////////////////////////////////////////////////////////////
template <typename CHAR, typename TRAITS>
friend std::basic_ostream<CHAR,TRAITS>& operator<< (std::basic_ostream<CHAR,TRAITS>& s, colour_t m)
{
// Ensure stream is a debug-console then apply background formatting
if (s.iword(console_stream<CHAR,TRAITS>::Ident))
static_cast<console_stream<CHAR,TRAITS>&>(s).setback(m);
return s;
}
};
//////////////////////////////////////////////////////////////////////////////////////////
//! \struct format - Debug-console stream formatting manipulator
//////////////////////////////////////////////////////////////////////////////////////////
struct format
{
//! \enum command_t - Formatting commands
enum command_t
{
heading, //!< Prints text in cyan
success, //!< Prints 'Success' in green
failure, //!< Prints 'Failure' in red
error, //!< Prints 'ERROR' in red
warning, //!< Prints 'WARNING' in blue
reset, //!< Resets formatting
push, //!< Pushes current formatting to the stack
pop, //!< Pops previously saved formatting from the stack
};
//////////////////////////////////////////////////////////////////////////////////////////
// ::operator<< friend
//! Modifies the formatting of a debug-console stream
//!
//! \param[in,out] &s - Debug-console stream
//! \param[in] m - Formatting
//! \return std::basic_ostream<CHAR,TRAITS> - Reference to 's'
//////////////////////////////////////////////////////////////////////////////////////////
template <typename CHAR, typename TRAITS>
friend std::basic_ostream<CHAR,TRAITS>& operator<< (std::basic_ostream<CHAR,TRAITS>& s, command_t m)
{
switch (m)
{
case heading: return s << backcol::black << (textcol::cyan|textcol::bold);
case success: return s << backcol::black << (textcol::green|textcol::bold) << "Success: " << textcol::white;
case failure: return s << backcol::black << (textcol::red|textcol::bold) << "Failure: " << textcol::white;
case error: return s << backcol::black << (textcol::red|textcol::bold) << "ERROR: " << textcol::white;
case reset: return s << backcol::black << textcol::white;
case push:
// Ensure stream is a debug-console then preserve formatting
if (s.iword(console_stream<CHAR,TRAITS>::Ident))
static_cast<console_stream<CHAR,TRAITS>&>(s).push();
break;
case pop:
// Ensure stream is a debug-console then restore formatting
if (s.iword(console_stream<CHAR,TRAITS>::Ident))
static_cast<console_stream<CHAR,TRAITS>&>(s).pop();
break;
}
return s;
}
};
//////////////////////////////////////////////////////////////////////////////////////////
// wtl::operator<<
//! Write a string to an output stream with different character traits
//!
//! \tparam CHAR - Output stream character type
//! \tparam TRAITS - Output stream character traits
//! \tparam STR_TRAITS - String character type
//! \tparam ALLOC - String allocator
//!
//! \param[in,out] &os - Output stream
//! \param[in] const& str - String
//! \return base& - Reference to 'os'
//////////////////////////////////////////////////////////////////////////////////////////
template <typename CHAR, typename OS_TRAITS, typename STR_TRAITS, typename ALLOC>
std::basic_ostream<CHAR,OS_TRAITS>& operator<<(std::basic_ostream<CHAR,OS_TRAITS>& os, const std::basic_string<CHAR,STR_TRAITS,ALLOC>& str)
{
return os.write(str.data(), str.size());
}
//////////////////////////////////////////////////////////////////////////////////////////
// wtl::operator <<
//! Writes an attribute enumeration to a debug console output stream
//!
//! \tparam CHAR - Output stream character type
//! \tparam TRAITS - Output stream character traits
//! \tparam T - Enumeration type
//!
//! \param[in,out] &c - Output stream
//! \param[in] val - Enumeration value
//! \return std::basic_ostream<CHAR,TRAITS>& - Reference to 'c'
//////////////////////////////////////////////////////////////////////////////////////////
template <typename CHAR, typename TRAITS, typename T, typename = enable_if_attribute_t<T>>
std::basic_ostream<CHAR,TRAITS>& operator << (std::basic_ostream<CHAR,TRAITS>& c, T val)
{
std::basic_ostringstream<CHAR> ss;
// Format as hex
ss << std::hex << std::uppercase << enum_cast(val);
return c << ss.str();
}
//////////////////////////////////////////////////////////////////////////////////////////
// wtl::operator <<
//! Writes a non-attribute enumeration to a debug console output stream
//!
//! \tparam CHAR - Output stream character type
//! \tparam TRAITS - Output stream character traits
//! \tparam T - Enumeration type
//!
//! \param[in,out] &c - Output stream
//! \param[in] val - Enumeration value
//! \return std::basic_ostream<CHAR,TRAITS>& - Reference to 'c'
//////////////////////////////////////////////////////////////////////////////////////////
template <typename CHAR, typename TRAITS, typename T, typename = enable_if_not_attribute_t<T>, typename = void>
std::basic_ostream<CHAR,TRAITS>& operator << (std::basic_ostream<CHAR,TRAITS>& c, T val)
{
return c << enum_cast(val);
}
//////////////////////////////////////////////////////////////////////////////////////////
// wtl::operator <<
//! Writes a caught-exception to a debug console output stream
//!
//! \tparam CHAR - Output stream character type
//! \tparam TRAITS - Output stream character traits
//!
//! \param[in,out] &c - Output stream
//! \param[in] const& ex - Caught exception wrapper
//! \return std::basic_ostream<CHAR,TRAITS>& - Reference to 'c'
//////////////////////////////////////////////////////////////////////////////////////////
template <typename CHAR, typename TRAITS>
std::basic_ostream<CHAR,TRAITS>& operator << (std::basic_ostream<CHAR,TRAITS>& c, const caught_exception& ex)
{
return c << format::push
<< '\n' << (textcol::red |textcol::bold) << "EXCEPTION: " << textcol::white << ex.Problem << "..." << ex.Cause
<< '\n' << (textcol::yellow|textcol::bold) << "CAUGHT: " << textcol::yellow << ex.source() << "..." << std::endl
<< format::pop;
}
//////////////////////////////////////////////////////////////////////////////////////////
// wtl::endl
//! Writes a new-line character to a debug console output stream, flushes the stream, and resets the character formatting
//!
//! \tparam CHAR - Output stream character type
//! \tparam TRAITS - Output stream character traits
//!
//! \param[in,out] &c - Output stream
//! \return console_stream<CHAR,TRAITS>& - Reference to 'c'
//////////////////////////////////////////////////////////////////////////////////////////
template <typename CHAR, typename TRAITS>
std::basic_ostream<CHAR,TRAITS>& endl(std::basic_ostream<CHAR,TRAITS>& c)
{
return c << '\n' << std::flush << format::reset;
}
} // WTL namespace
#endif // WTL_CONSOLE_HPP
|
b8b619c480d633720421bc8c9e87f545fdc9aa60
|
3b027f2f1f1221a5bc262daf0533d6f7fe8e8c40
|
/DynamicPatcherInjectorDLL.cpp
|
512cebed51f8d0d4674f6dd4b7f5de9893e76166
|
[
"CC-BY-4.0"
] |
permissive
|
bryant1410/DynamicPatcher
|
e3bbc2044921f815fe784a559a77c681463d9cf1
|
e6a4eed594e89481ac306df02138deac0e3ed79c
|
refs/heads/master
| 2021-01-19T19:50:37.027577
| 2017-04-16T23:25:11
| 2017-04-16T23:25:11
| 88,448,745
| 0
| 0
| null | 2017-04-16T23:25:12
| 2017-04-16T23:25:12
| null |
UTF-8
|
C++
| false
| false
| 538
|
cpp
|
DynamicPatcherInjectorDLL.cpp
|
// created by i-saint
// distributed under Creative Commons Attribution (CC BY) license.
// https://github.com/i-saint/DynamicPatcher
#include <windows.h>
#include "DynamicPatcher.h"
dpAPI void dpBeginPeriodicUpdate();
dpAPI void dpEndPeriodicUpdate();
BOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpvReserved)
{
if(fdwReason==DLL_PROCESS_ATTACH) {
dpBeginPeriodicUpdate();
}
else if(fdwReason==DLL_PROCESS_DETACH) {
dpEndPeriodicUpdate();
}
return TRUE;
}
|
48d0bc09a4ad9fbe62b4d637a3516395fa6a103c
|
5ccbe86a8e2932e8500ecce2f41327ea0ce2a981
|
/Src/UI/TextOutput.cpp
|
c33e4011edcba98a8011f06e04e18fa8f62005d4
|
[] |
no_license
|
TheChriggu/SlayingDemons_
|
753dffe67d066675f6e2a835869bece473221d52
|
b448778bc9e294f4eb0d9e262827abd85e48cb19
|
refs/heads/master
| 2022-07-12T11:29:47.658494
| 2020-05-14T15:52:50
| 2020-05-14T15:52:50
| 259,582,263
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 7,218
|
cpp
|
TextOutput.cpp
|
//
// Created by christian.heusser on 06.11.2019.
//
#include "TextOutput.h"
#include <iostream>
#include <memory>
#include <Event/EventSystem.h>
#include <Event/TextOutputCreatedEventArgs.h>
#include <Event/LineToOutputEventArgs.h>
#include <ScriptEngine/ScriptEngine.h>
#include <Event/FontsCreatedEventArgs.h>
#include <Event/ColorsCreatedEventArgs.h>
#include <Event/SetStageEventArgs.h>
// TODO(FK): clean up name
sd::TextOutput::TextOutput(sf::Vector2f position, sf::Vector2f size, sf::Color color)
: DrawableObject("text-output")
, Subscriber()
, position_(position)
{
event_handler_ = CREATE_EVENT_HANDLER(
if (e->type == EventArgs::Type::LINE_TO_OUTPUT) {
auto arg = std::dynamic_pointer_cast<LineToOutputEventArgs>(e);
enqueue_line (arg->line);
}
if (e->type == EventArgs::Type::FONTS_CREATED) {
auto arg = std::dynamic_pointer_cast<FontsCreatedEventArgs>(e);
fonts_ = Sp<Font>(arg->fonts);
}
if (e->type == EventArgs::Type::COLORS_CREATED) {
auto arg = std::dynamic_pointer_cast<ColorsCreatedEventArgs>(e);
colors_ = Sp<Colors>(arg->colors);
}
if(e->type == EventArgs::Type::CURRENT_FONT_CHANGED)
{
reformat();
}
if(e->type == EventArgs::Type::CURRENT_COLOR_CHANGED)
{
reformat();
}
if(e->type == EventArgs::Type::SET_STAGE)
{
auto arg = std::dynamic_pointer_cast<SetStageEventArgs>(e);
switch(arg->stage)
{
case 0:
max_size_.x = 1024;
max_size_.y = 435;
offset_ = sf::Vector2f(10, 55);
break;
case 1:
max_size_.x = 1024;
max_size_.y = 435;
offset_ = sf::Vector2f(10, 55);
break;
case 2:
max_size_.x = 1024;
max_size_.y = 500;
offset_ = sf::Vector2f(0, 15);
break;
case 3:
max_size_.x = 1024;
max_size_.y = 500;
offset_ = sf::Vector2f(0, 15);
break;
}
}
if(e->type == EventArgs::Type::RESET_OUTPUT_TIMER)
{
print_first_in_queue();
}
);
REGISTER_EVENT_HANDLER();
max_size_.x = size.x -20;
max_size_.y = 435;
text_tex_ = std::make_shared<sf::RenderTexture>();
text_sprite_ = std::make_shared<sf::Sprite>();
offset_ = sf::Vector2f(10, 55);
line_queue_ = std::make_shared<std::vector<std::string>>();
clock_ = std::make_shared<sf::Clock>();
clock_->restart();
}
bool sd::TextOutput::setup() {
//ScriptEngine::get().register_all_timeable(1, 0.25f, "print_line", &TextOutput::enqueue_line, this);
ScriptEngine::get().register_all("print_line", &TextOutput::enqueue_line, this);
lines_.push_back(std::make_shared<FormattedLine>(
"",
sf::Vector2f(position_ + offset_),
max_size_, fonts_, colors_));
// Trigger TextOutput Created Event
EventSystem::get().trigger(std::make_shared<TextOutputCreatedEventArgs>(weak_from_this()));
auto table = ScriptEngine::get().get_script("config")->get_table("window")->as<sol::table>();
text_tex_->create(table["size"]["x"], table["size"]["y"]);
text_sprite_->setTexture(text_tex_->getTexture());
//one second interval between printing enqueued lines
/*auto routine = std::make_shared<Routine>( Routine(nullptr, 1.5f,
std::function<bool(Sp<Routine>)>
(
[this](Sp<Routine> this_routine)
{
print_first_in_queue();
return Routine::restart;
}
)
)
);
RoutineManager::get().start_routine(routine);*/
return DrawableObject::setup ();
}
void sd::TextOutput::draw_to(Sp<sf::RenderTarget> window) const {
if(clock_->getElapsedTime().asSeconds() >= 0.85f)
{
clock_->restart();
auto args = std::make_shared<EventArgs>();
args->type = EventArgs::Type::RESET_OUTPUT_TIMER;
EventSystem::get().trigger(args);
}
text_tex_->clear(sf::Color::Transparent);
for (const auto& line : lines_)
{
line->draw_to (text_tex_);
}
text_tex_->display();
if (shader_procedure_)
{
shader_procedure_->process (window.get (), text_sprite_.get ());
} else
{
window->draw(*text_sprite_);
}
}
void sd::TextOutput::add_line(std::string string) {
auto new_line = std::make_shared<FormattedLine>(
string, sf::Vector2f(
(position_ + offset_).x,
lines_.back ()->get_rect ().top + lines_.back ()->get_rect ().height),
max_size_,fonts_, colors_
);
//format line
lines_.push_back(new_line);
while(get_size ().y > max_size_.y)
{
float distance = lines_.front ()->get_rect ().height;
move_vertical (-distance);
lines_.pop_front();
}
}
void sd::TextOutput::print_line(std::string string) {
//sf::String temp(string);
add_line (string);
}
void sd::TextOutput::handle(sf::Event event) {
for(auto line : lines_)
{
line->handle(event);
}
}
sf::Vector2f sd::TextOutput::get_position() {
return position_;
}
sf::Vector2f sd::TextOutput::get_size() {
sf::Vector2f ret_val;
ret_val.x = 0;
ret_val.y = 0;
for (const auto& line : lines_)
{
sf::FloatRect rect = line->get_rect ();
if (rect.width > ret_val.x)
{
ret_val.x = rect.width;
}
ret_val.y += rect.height;
}
return ret_val;
}
void sd::TextOutput::move_vertical(float distance) {
for(const auto& line : lines_){
line->move_vertical (distance);
}
}
void sd::TextOutput::reformat() {
std::vector<std::string> lines;
for (auto line : lines_)
{
lines.push_back(line -> get_line());
}
lines_.clear();
lines_.push_back(std::make_shared<FormattedLine>(
"",
sf::Vector2f(position_ + offset_),
max_size_, fonts_, colors_));
for (auto line : lines)
{
add_line(line);
std::cout << line << "\n";
}
}
void sd::TextOutput::enqueue_line(std::string string) {
line_queue_->push_back(string);
}
void sd::TextOutput::print_first_in_queue() {
if(line_queue_->size() > 0)
{
add_line(line_queue_->front());
line_queue_->erase(line_queue_->begin());
}
}
bool sd::TextOutput::has_queue() {
return line_queue_->size() > 0;
}
|
92cc0deb1465ef89e5ff4b34ffa5e2d7180eed50
|
6b2a8dd202fdce77c971c412717e305e1caaac51
|
/solutions_5639104758808576_0/C++/cmonkey/GCJ2015-Q-A.cpp
|
070fe8f47fb070c39eb2678602d089c99dc4982d
|
[] |
no_license
|
alexandraback/datacollection
|
0bc67a9ace00abbc843f4912562f3a064992e0e9
|
076a7bc7693f3abf07bfdbdac838cb4ef65ccfcf
|
refs/heads/master
| 2021-01-24T18:27:24.417992
| 2017-05-23T09:23:38
| 2017-05-23T09:23:38
| 84,313,442
| 2
| 4
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 672
|
cpp
|
GCJ2015-Q-A.cpp
|
#include <cstdlib>
#include <cstdio>
char shy[1010];
int main(){
int T, t, smax, sum, ans, i;
FILE* fin = fopen("A-small-attempt1.in", "r");
FILE* fout = fopen("A.out", "w");
fscanf(fin, "%d", &T);
for (t = 1; t <= T; t++){
fscanf(fin, "%d %s", &smax, shy);
ans = sum = 0;
for (i = 0; shy[i] && i <= smax; i++){
if (shy[i] == '0') continue;
if (sum < i){
ans += i - sum;
sum = i;
}
sum += shy[i] - '0';
}
fprintf(fout, "Case #%d: %d\n", t, ans);
}
fclose(fin);
fclose(fout);
return 0;
}
|
3c23b369e545c176e83a964d0150b60fde182d9a
|
cd705effab268c82f9299c06d4fce2f3f7ef2fc2
|
/comp345-proj/PlayerBase.h
|
804b05b74bd8a4b0325b711dea5a81776622d36f
|
[] |
no_license
|
hrachyahakobyan/Pandemic
|
bd9c8d6f63e4912ab179dcde76e2312d582c5a8c
|
b962cbb60ded8e87d104a2efeb73273b6b478470
|
refs/heads/master
| 2021-01-20T12:09:34.029896
| 2017-04-18T04:44:00
| 2017-04-18T04:44:00
| 83,480,316
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 3,498
|
h
|
PlayerBase.h
|
#pragma once
#include "Role.h"
#include "detail\Deck.h"
#include "ReferenceCard.h"
#include "Cards.h"
namespace pan{
/**
* @brief Base class for player objects.
* @author Hrachya Hakobyan
*/
class PlayerBase {
public:
virtual ~PlayerBase();
bool operator==(const PlayerBase&) const;
inline bool operator!=(const PlayerBase&) const;
inline const std::string& getName() const;
inline void setName(const std::string& name);
inline CityIndex getLocation() const;
inline void setLocation(CityIndex);
inline detail::Deck<CardBasePtr>& getCards();
inline const detail::Deck<CardBasePtr>& getCards() const;
inline void setCards(const detail::Deck<CardBasePtr>&);
virtual const RoleBase& getRole() const = 0;
std::string description() const;
const PlayerIndex index;
const ReferenceCard referenceCard;
bool hasCityCard(CityIndex) const;
bool hasEventCard(EventType type) const;
std::shared_ptr<EventCard> removeEventCard(EventType type);
std::shared_ptr<CityCard> removeCityCard(CityIndex index);
std::size_t countCardsMatching(const CardBase& card) const;
std::size_t countCardsMatchingRegion(RegionIndex index) const;
detail::Deck<std::shared_ptr<CityCard>> removeCardsMatchingRegion(RegionIndex region, std::size_t count);
friend class boost::serialization::access;
template<class Archive>
void serialize(Archive & ar, const unsigned int /* file_version */){
ar.template register_type<pan::CardBase>();
ar.template register_type<pan::detail::Deck<pan::CardBasePtr>>();
ar.template register_type<pan::InfectionCard>();
ar.template register_type<pan::EpidemicCard>();
ar.template register_type<pan::EventCard>();
ar.template register_type<pan::CityCard>();
ar & BOOST_SERIALIZATION_NVP(name);
ar & BOOST_SERIALIZATION_NVP(location);
ar & BOOST_SERIALIZATION_NVP(cards);
ar & boost::serialization::make_nvp("index", const_cast<PlayerIndex&>(index));
}
protected:
PlayerBase(PlayerIndex index);
PlayerBase(PlayerIndex index, const std::string& name);
detail::Deck<CardBasePtr> cards;
std::string name;
CityIndex location;
#ifdef _DEBUG
#ifndef DISABLE_TESTS
FRIEND_TESTS
#endif
#endif
};
typedef std::shared_ptr<pan::PlayerBase> PlayerPtr;
bool PlayerBase::operator!=(const PlayerBase& o) const
{
return !((*this) == o);
}
const std::string& PlayerBase::getName() const
{
return name;
}
void PlayerBase::setName(const std::string& name)
{
this->name = name;
}
CityIndex PlayerBase::getLocation() const
{
return location;
}
void PlayerBase::setLocation(CityIndex loc)
{
this->location = loc;
}
detail::Deck<CardBasePtr>& PlayerBase::getCards()
{
return cards;
}
const detail::Deck<CardBasePtr>& PlayerBase::getCards() const
{
return cards;
}
void PlayerBase::setCards(const detail::Deck<CardBasePtr>& cards)
{
this->cards = cards;
}
}
/**
* Since the class does not have default constructors, we need this
* to avoid compilation errors when attempting to (de)serialize
* types of PlayerBase*. This methods do not do anything, since
* we are not going to have actual PlayerBase instances in the program.
*/
namespace boost {
namespace serialization {
template<class Archive>
inline void save_construct_data(
Archive & ar, const pan::PlayerBase * p, const unsigned int file_version
){
}
template<class Archive>
inline void load_construct_data(
Archive & ar, pan::PlayerBase * p, const unsigned int file_version
){
}
}
}
|
89f8d5dfa9c5af1d636b3303b7c307c7985037d4
|
c40bb35033f6b88a1cb78b3baa1999f5cbf7fdb9
|
/City.h
|
d6a15eeec61b34a7d5b501c1465b8057e0065be0
|
[] |
no_license
|
7NGU/GitTest
|
21f1ce59e8dff59ce60f05ca8b759997e6b4c33b
|
a9fbaa46c4da53d0bbd3c71f1bdbc122792eddd0
|
refs/heads/master
| 2021-04-04T12:34:57.183809
| 2020-03-19T09:43:27
| 2020-03-19T09:43:27
| 248,457,708
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,429
|
h
|
City.h
|
///
/// @file City.h
/// @author lemon(haohb13@gmail.com)
/// @date 2019-05-28 21:15:53
///
#pragma once
#include "Types.h"
#include <vector>
using std::vector;
namespace warcraft
{
class City
{
public:
City(size_t id, size_t elements = 0)
: _flag(Color::NOTSET)
, _id(id)
, _elements(elements)
, _redWinCount(0)
, _blueWinCount(0)
{}
size_t getWarriorAmount() const { return _redWarriors.size() + _blueWarriors.size(); }
vector<WarriorPtr> & getRedWarriors() { return _redWarriors; }
vector<WarriorPtr> & getBlueWarriors() { return _blueWarriors; }
WarriorPtr getSoloWarrior()
{
if(_redWarriors.size() == 0)
return *_blueWarriors.begin();
else
return *_redWarriors.begin();
}
void takenBy(WarriorPtr warrior);
void produceElements();
void attach(WarriorPtr);
void detach(WarriorPtr);
void startBattle();
size_t getId() const { return _id; }
Color getFlag() const { return _flag; }
private:
void battle(WarriorPtr warrior1, WarriorPtr warrior2);
bool isChangingFlag(WarriorPtr warrior);
private:
Color _flag;//旗子颜色
size_t _id;
size_t _elements;//生命元数量
size_t _redWinCount;
size_t _blueWinCount;
vector<WarriorPtr> _redWarriors;
vector<WarriorPtr> _blueWarriors;
//vector<WarriorPtr> _warriors;
};
class CityView
{
public:
CityView(City * city) : _city(city) {}
void showFlag() const;
private:
City * _city;
};
}//end of namespace warcraft
|
307ab15d243db3abb7c26b720ba0e0030f2be2de
|
83dbc5115cf7e8a48aaff3c78b8bb530dc72bc32
|
/src/widgets/colorarea.h
|
5f93e086bc978475235454e3845b1aea3ff72891
|
[] |
no_license
|
Gris87/ProtocolCreator
|
70ff4b019de36688985ac04fe69a93e5b42f546d
|
b178307776f68d9fe1a1949ccfc74a9ee8911b93
|
refs/heads/master
| 2020-06-06T12:53:58.698298
| 2012-11-05T17:07:49
| 2012-11-05T17:07:49
| 2,945,350
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 856
|
h
|
colorarea.h
|
#ifndef COLORAREA_H
#define COLORAREA_H
#include <QFrame>
#include <QPalette>
#include <QPainter>
#include <QScreen>
#include <QColorDialog>
#include <QMouseEvent>
#include <QDesktopWidget>
#include <QGridLayout>
#include <QApplication>
class ColorArea : public QFrame
{
Q_OBJECT
public:
explicit ColorArea(QWidget *parent = 0);
void setColor(QColor aColor);
QColor color();
bool needDrawFrame;
bool popupAllowed;
bool selectAllowed;
quint8 popupCount;
quint8 popupCellSize;
protected:
void mousePressEvent(QMouseEvent *event);
void paintEvent(QPaintEvent *event);
QWidget *aPopupWidget;
private slots:
void cellClicked(ColorArea *aArea);
signals:
void clicked(ColorArea *aArea);
void rightClicked(ColorArea *aArea);
void colorChanged(const QColor &aColor);
};
#endif // COLORAREA_H
|
dad45dccfce8782fc8ea1d71d1857979ccad90cb
|
b13f3102af4ab13423baafb756f233af2076e0d3
|
/src/fonts/FreetypeFont.cpp
|
b481ec2cedd8223547c197c083cdd44e7c8173d7
|
[
"MIT"
] |
permissive
|
feliwir/charta-pdf
|
3adc69df40e87b8404229d5d2f12227c19e2211d
|
d9102224c5d922b559373f91d087ef72caf36b41
|
refs/heads/master
| 2023-06-11T23:43:30.060533
| 2021-06-23T05:52:49
| 2021-06-23T05:52:49
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,229
|
cpp
|
FreetypeFont.cpp
|
#include "FreetypeFont.hpp"
#include <iostream>
charta::pdf::FreetypeFont::FreetypeFont(FT_Face face, uint8_t *data, size_t size)
: m_face(face), m_data(data, data + size)
{
auto type = std::string(FT_Get_Font_Format(face));
if (type == "TrueType")
{
m_subtype = FontType::TrueType;
}
switch (m_subtype)
{
case FontType::TrueType:
loadOpenTypeTables();
break;
}
// Set the unicode charmap
if (FT_Select_Charmap(m_face, FT_ENCODING_UNICODE) != 0)
{
// TODO: error handling
}
}
void charta::pdf::FreetypeFont::loadOpenTypeTables()
{
m_postScriptTable = static_cast<TT_Postscript *>(FT_Get_Sfnt_Table(m_face, ft_sfnt_post));
m_os2Table = static_cast<TT_OS2 *>(FT_Get_Sfnt_Table(m_face, ft_sfnt_os2));
m_pcltTable = static_cast<TT_PCLT *>(FT_Get_Sfnt_Table(m_face, ft_sfnt_pclt));
}
charta::pdf::FreetypeFont::~FreetypeFont()
{
FT_Done_Face(m_face);
}
charta::pdf::FontType charta::pdf::FreetypeFont::getSubtype()
{
return m_subtype;
}
short charta::pdf::FreetypeFont::getAscent()
{
return m_face->ascender;
}
short charta::pdf::FreetypeFont::getDescent()
{
return m_face->descender;
}
const char *charta::pdf::FreetypeFont::getFontName()
{
const char *name = FT_Get_Postscript_Name(m_face);
return name;
}
double charta::pdf::FreetypeFont::getItalicAngle()
{
return (m_postScriptTable != nullptr) ? (m_postScriptTable->italicAngle / double(1 << 16)) : 0.0;
}
std::optional<short> charta::pdf::FreetypeFont::getCapHeight()
{
if (m_os2Table != nullptr)
{
return m_os2Table->sCapHeight;
}
if (m_pcltTable != nullptr)
{
return m_pcltTable->CapHeight;
}
return {};
}
std::optional<short> charta::pdf::FreetypeFont::getxHeight()
{
if (m_os2Table != nullptr)
{
return m_os2Table->sxHeight;
}
if (m_pcltTable != nullptr)
{
return m_pcltTable->xHeight;
}
return {};
}
bool charta::pdf::FreetypeFont::addCodepoint(uint32_t codepoint)
{
auto glyph_index = FT_Get_Char_Index(m_face, codepoint);
if (glyph_index == 0)
{
return false;
}
m_usedGylphs.insert(glyph_index);
return true;
}
|
9bac75548e77dbeee029f457e160af9948e13ce0
|
6cea3597595754b7c77d600e918c5f4c54a601be
|
/Cassandra Client Code/RtConnectionObj.hpp
|
0e20b0b7f4f96e7f67ff093e57d20c5579c45492
|
[] |
no_license
|
LazyHippogriff/Cassandra-Ignite
|
f11cbc17f1719f74fdc8be77f1b4ba8b496a7c75
|
a56fa07d60e63c94edd7c77acc8e2bca721a7575
|
refs/heads/master
| 2020-03-14T21:57:00.969571
| 2018-05-02T11:23:44
| 2018-05-02T11:23:44
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 547
|
hpp
|
RtConnectionObj.hpp
|
#ifndef __RT_CONNECTION_OBJ_HPP__
#define __RT_CONNECTION_OBJ_HPP__
#include<cassandra.h>
#include<stdio.h>
#include<iostream>
using namespace std;
class RtConnectionObj
{
static RtConnectionObj * m_instance;
public :
static CassCluster* ms_cluster;
static CassSession* ms_session;
static RtConnectionObj * rtReturnInstance();
static CassSession* rtGetSession();
// static void rtSetSession(CassSession *)
static void initilizeSession();
RtConnectionObj();
~RtConnectionObj();
};
#endif // __RT_CONNECTION_OBJ_HPP__
|
d394895045df5e7c31d2c7b280804ae7b0fd4c2a
|
2d0bada349646b801a69c542407279cc7bc25013
|
/src/vai_library/cpu_task/ops/l2norm/l2norm.cpp
|
dc7d736f917d45014a2ab976d813929a8dc398f7
|
[
"BSD-3-Clause",
"LicenseRef-scancode-generic-cla",
"BSD-3-Clause-Open-MPI",
"LicenseRef-scancode-free-unknown",
"Libtool-exception",
"GCC-exception-3.1",
"LicenseRef-scancode-mit-old-style",
"OFL-1.1",
"JSON",
"LGPL-2.1-only",
"LGPL-2.0-or-later",
"ICU",
"LicenseRef-scancode-other-permissive",
"GPL-2.0-or-later",
"GPL-3.0-only",
"LicenseRef-scancode-issl-2018",
"MIT",
"LGPL-2.1-or-later",
"LicenseRef-scancode-unicode",
"LGPL-3.0-only",
"LicenseRef-scancode-warranty-disclaimer",
"GPL-3.0-or-later",
"Zlib",
"BSD-Source-Code",
"ClArtistic",
"LicenseRef-scancode-unknown-license-reference",
"ISC",
"NCSA",
"LicenseRef-scancode-proprietary-license",
"GPL-2.0-only",
"CC-BY-4.0",
"FSFULLR",
"Minpack",
"Unlicense",
"BSL-1.0",
"NAIST-2003",
"Apache-2.0",
"LicenseRef-scancode-protobuf",
"LicenseRef-scancode-public-domain",
"Libpng",
"Spencer-94",
"BSD-2-Clause",
"Intel",
"GPL-1.0-or-later",
"MPL-2.0"
] |
permissive
|
Xilinx/Vitis-AI
|
31e664f7adff0958bb7d149883ab9c231efb3541
|
f74ddc6ed086ba949b791626638717e21505dba2
|
refs/heads/master
| 2023-08-31T02:44:51.029166
| 2023-07-27T06:50:28
| 2023-07-27T06:50:28
| 215,649,623
| 1,283
| 683
|
Apache-2.0
| 2023-08-17T09:24:55
| 2019-10-16T21:41:54
|
Python
|
UTF-8
|
C++
| false
| false
| 2,101
|
cpp
|
l2norm.cpp
|
/*
* Copyright 2022-2023 Advanced Micro Devices Inc.
*
* 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 <cmath>
#include <iostream>
#include "vart/op_imp.h"
#include "vart/runner_helper.hpp"
using namespace std;
namespace {
inline void L2_normalization(vart::simple_tensor_buffer_t<float> input,vart::simple_tensor_buffer_t<float> output, int channel, int group) {
for (int i = 0; i < group; ++i) {
float sum = 0.0;
for (int j = 0; j < channel; ++j) {
int pos = i*channel + j;
float temp = static_cast<float>(input.data[pos]);
sum += temp*temp;
}
float var = sqrt(sum);
for (int j = 0; j < channel; ++j) {
int pos = i*channel + j;
output.data[pos] = static_cast<float>(input.data[pos]) / var;
}
}
}
struct MyOpImp : public vart::experimental::OpImpBase {
MyOpImp(const xir::Op* op, xir::Attrs* attrs)
: vart::experimental::OpImpBase{op, attrs} {}
int calculate(vart::simple_tensor_buffer_t<float> result,
vart::simple_tensor_buffer_t<float> input) {
auto input_shape = input.tensor->get_shape();
auto output_shape = result.tensor->get_shape();
auto num_of_dims = input_shape.size();
CHECK_EQ(num_of_dims, output_shape.size());
for (auto dim = 0u; dim < num_of_dims; ++dim) {
CHECK_EQ(input_shape[dim], output_shape[dim]);
}
auto channels = output_shape[3];
auto height = output_shape[1];
auto width = output_shape[2];
L2_normalization(input, result, channels, height * width);
return 0;
}
};
} // namespace
DEF_XIR_OP_IMP(MyOpImp)
|
1d1010b8fa748d3d56eb11d16967fd9c543f13cd
|
0b706b6e3561f5defbc35bb675c158046995ccf5
|
/src/UI/main.cpp
|
70bc2a823eba62eac9006ed0b1534ba4bbf0c290
|
[] |
no_license
|
leihtg/fmj_cpp
|
ce3baa87353aa1eccc298fc44c93f6ffe64dd389
|
3e3935d37bc63f078cdf0498b807469dbb25e820
|
refs/heads/master
| 2020-07-29T21:44:22.357817
| 2018-09-14T14:57:59
| 2018-09-14T14:57:59
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 224
|
cpp
|
main.cpp
|
#include <QtGui/QApplication>
#include "fmjwindow.h"
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
fmjWindow w;
w.setWindowTitle("fmj");
w.show();
w.run();
return 0;/*a.exec()*/;
}
|
19b5b84c79cd92104012efe8f333778af0b69d2c
|
ec2d6d2268d839932997c130aaaee0db0110936e
|
/cezar/main.cpp
|
159cf5f7571ee930cf6ad360d160bbe83b6669d3
|
[] |
no_license
|
gaby22v/C-
|
803256febf47dff3d90d208ebc288faa4fbeb725
|
aacc7c22e2b2e61d098e0722ba96036da52c1772
|
refs/heads/master
| 2016-09-15T22:54:37.686567
| 2016-03-12T23:37:42
| 2016-03-12T23:37:42
| 27,445,556
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 850
|
cpp
|
main.cpp
|
#include <iostream.h>
#include <conio.h>
#include <stdio.h>
#include <string.h>
#include <iomanip.h>
int n;
void alfabet_initial()
{
for(char i=65;i<=122;i++)
{
if (i!=91&i!=92&i!=93&i!=94&i!=95&i!=96)
{
cout<<i<<' ';
}
}
}
void alfabet_defazat()
{
cout<<endl;
cout<<"defazajul alfabetului "<<endl;
cout<<"n=";cin>>n;
for(char j=65;j<=122;j++)
{
if (j+n>122)
if(char(j+n)==' ') cout<<' ';
else
cout<<char(j-58+n)<<' ';
else
if (j+n!=91&j+n!=92&j+n!=93&j+n!=94&j+n!=95&j+n!=96) cout<<char(j+n)<<' ';
}
}
void afisare1()
{
char x[50];
cout<<"x=";gets(x);
for(char j=0;j<strlen(x);j++)
{
if ((x[j]+n>122)&('#'==32))
cout<<char(x[j]-58+n)<<' ';
else
cout<<char(x[j]+n);
}
}
int main()
{
char n,i;
char x[50];
alfabet_initial();
alfabet_defazat();
cout<<endl<<endl;
afisare1();
cout<<endl;
getch();
}
|
07261b6e692a733980e5ef9b09f8549fd60acbcf
|
d4254d0a4206a6b15a670d94d0f554b26dc67487
|
/year2/COS2614/Assignment 1/question2/coordinate.h
|
9bd4196450159d0b90cc893ada4f591c37c123d5
|
[] |
no_license
|
luyandamncube/UNISA
|
0c0378bedc2de72f4e478b8c4635b204ee3cc1e4
|
770647e583f6c786449729bb7ed096206136f346
|
refs/heads/master
| 2022-02-12T02:20:11.762040
| 2022-01-31T02:27:29
| 2022-01-31T02:27:29
| 244,408,008
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 375
|
h
|
coordinate.h
|
#ifndef COORDINATE_H
#define COORDINATE_H
#include <QString>
class Coordinate {
private:
int degrees;
int minutes;
int seconds;
QChar direction;
public:
//Constructor
Coordinate(int degrees, int minutes, int seconds, QChar direction);
QString toString();
double toDecimal();
};
#endif // COORDINATE_H
|
9e282fcf3d8cd43c1565b77664eb39dba0f53555
|
7c910ee551b968ff50c01f7cfd8add84cbdd1142
|
/include/byom/ext/qmap.hpp
|
2bc12dbfa6c600365a5412ec3b9458bc5c4f6368
|
[
"ISC"
] |
permissive
|
purpleKarrot/BYOM
|
a9a4fc4b12db63b1054d632fe4a6e78082489462
|
1de5f53a1185b37676d76399bd67ff9e08ad828a
|
refs/heads/master
| 2021-01-10T04:44:12.045122
| 2016-02-05T20:27:15
| 2016-02-05T21:48:40
| 47,145,374
| 2
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,649
|
hpp
|
qmap.hpp
|
// Copyright (c) 2015, Daniel Pfeifer <daniel@pfeifer-mail.de>
//
// Permission to use, copy, modify, and/or distribute this software for any
// purpose with or without fee is hereby granted, provided that the above
// copyright notice and this permission notice appear in all copies.
//
// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
// ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
// ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
// OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
#ifndef BYOM_EXT_QMAP_HPP
#define BYOM_EXT_QMAP_HPP
#include <byom/ext/fallback.hpp>
#include <byom/ext/qstring.hpp>
#include <QMap>
namespace byom {
template <typename Value>
struct ext<QMap<QString, Value>> : detail::fallback
{
using model_t = QMap<QString, Value>;
static bool empty_impl(model_t const& model)
{
return model.isEmpty();
}
static Value const& at_impl(model_t const& model, std::string const& name)
{
auto const it = model.find(QString::fromStdString(name));
if (it == model.end()) {
throw std::out_of_range{ "out of range" };
}
return it.value();
}
static void for_each_impl(model_t const& model, visit_function const& visit)
{
for (auto i = model.begin(); i != model.end(); ++i) {
visit(i.key(), i.value());
}
}
};
} // namespace byom
#endif /* BYOM_EXT_QMAP_HPP */
|
3a544ac7253160529a2c88595a09b3d0100c0958
|
d3056a23d41e2f43a77121663179bc7eaf9eec34
|
/BOJ/boj_1697.cpp
|
718684f4f04490b2d865c5c9783c4168deeb6e1a
|
[] |
no_license
|
eojine/algorithm
|
7e243e1993a16a3bcf33ea1920084846455dc93d
|
5ed225d0f9f15a2c7e92059630cc63fdb017ac0c
|
refs/heads/master
| 2021-06-24T08:18:45.804004
| 2020-12-31T07:45:23
| 2020-12-31T07:45:23
| 182,960,328
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 844
|
cpp
|
boj_1697.cpp
|
#include <cstdio>
#include <queue>
using namespace std;
queue<int> q;
int visit[100001];
int n, k;
int cnt = 0;
int main() {
scanf("%d %d", &n, &k);
q.push(n);
visit[n] = 1;
while (!q.empty()) {
int size = q.size();
for (int i = 0; i < size; ++i) {
int v = q.front();
q.pop();
if (v == k)
printf("%d", cnt);
if (v - 1 >= 0 && visit[v - 1] == 0) {
q.push(v - 1);
visit[v - 1] = 1;
}
if (v + 1 <= 100000 && visit[v + 1] == 0) {
q.push(v + 1);
visit[v + 1] = 1;
}
if (v * 2 <= 100000 && visit[v * 2] == 0) {
q.push(v * 2);
visit[v * 2] = 1;
}
}
cnt++;
}
return 0;
}
|
47fb6ef58d585420961ccc1d705f48f4a3ae06a6
|
2b1b459706bbac83dad951426927b5798e1786fc
|
/src/proc/tests/chromiumos/syscalls/socket_test.cc
|
9befdf302ff12361cecae35592fd6ee523e14ed2
|
[
"BSD-2-Clause"
] |
permissive
|
gnoliyil/fuchsia
|
bc205e4b77417acd4513fd35d7f83abd3f43eb8d
|
bc81409a0527580432923c30fbbb44aba677b57d
|
refs/heads/main
| 2022-12-12T11:53:01.714113
| 2022-01-08T17:01:14
| 2022-12-08T01:29:53
| 445,866,010
| 4
| 3
|
BSD-2-Clause
| 2022-10-11T05:44:30
| 2022-01-08T16:09:33
|
C++
|
UTF-8
|
C++
| false
| false
| 4,935
|
cc
|
socket_test.cc
|
// Copyright 2022 The Fuchsia 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.h>
#include <sys/epoll.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <sys/un.h>
#include <unistd.h>
#include <asm-generic/socket.h>
#include <gtest/gtest.h>
TEST(UnixSocket, ReadAfterClose) {
int fds[2];
ASSERT_EQ(0, socketpair(AF_UNIX, SOCK_STREAM, 0, fds));
ASSERT_EQ(1, write(fds[0], "0", 1));
ASSERT_EQ(0, close(fds[0]));
char buf[1];
ASSERT_EQ(1, read(fds[1], buf, 1));
ASSERT_EQ('0', buf[0]);
ASSERT_EQ(0, read(fds[1], buf, 1));
}
TEST(UnixSocket, ReadAfterReadShutdown) {
int fds[2];
ASSERT_EQ(0, socketpair(AF_UNIX, SOCK_STREAM, 0, fds));
ASSERT_EQ(1, write(fds[0], "0", 1));
ASSERT_EQ(0, shutdown(fds[1], SHUT_RD));
char buf[1];
ASSERT_EQ(1, read(fds[1], buf, 1));
ASSERT_EQ('0', buf[0]);
ASSERT_EQ(0, read(fds[1], buf, 1));
}
TEST(UnixSocket, HupEvent) {
int fds[2];
ASSERT_EQ(0, socketpair(AF_UNIX, SOCK_STREAM, 0, fds));
int epfd = epoll_create1(0);
ASSERT_LT(-1, epfd);
epoll_event ev = {EPOLLIN, {.u64 = 42}};
ASSERT_EQ(0, epoll_ctl(epfd, EPOLL_CTL_ADD, fds[0], &ev));
epoll_event outev = {0, {.u64 = 0}};
int no_ready = epoll_wait(epfd, &outev, 1, 0);
ASSERT_EQ(0, no_ready);
close(fds[1]);
no_ready = epoll_wait(epfd, &outev, 1, 0);
ASSERT_EQ(1, no_ready);
ASSERT_EQ(EPOLLIN | EPOLLHUP, outev.events);
ASSERT_EQ(42ul, outev.data.u64);
close(fds[0]);
close(epfd);
}
struct read_info_spec {
unsigned char* mem;
size_t length;
size_t bytes_read;
int fd;
};
void* reader(void* arg) {
read_info_spec* read_info = reinterpret_cast<read_info_spec*>(arg);
while (read_info->bytes_read < read_info->length) {
size_t to_read = read_info->length - read_info->bytes_read;
fflush(stdout);
ssize_t bytes_read = read(read_info->fd, read_info->mem + read_info->bytes_read, to_read);
EXPECT_LT(-1, bytes_read);
if (bytes_read < 0) {
return nullptr;
}
read_info->bytes_read += bytes_read;
}
return nullptr;
}
TEST(UnixSocket, BigWrite) {
const size_t write_size = 300000;
unsigned char* send_mem = new unsigned char[write_size];
ASSERT_TRUE(send_mem != nullptr);
for (size_t i = 0; i < write_size; i++) {
send_mem[i] = 0xff & random();
}
int fds[2];
ASSERT_EQ(0, socketpair(AF_UNIX, SOCK_STREAM, 0, fds));
read_info_spec read_info;
read_info.mem = new unsigned char[write_size];
bzero(read_info.mem, sizeof(unsigned char) * write_size);
ASSERT_TRUE(read_info.mem != nullptr);
read_info.length = write_size;
read_info.fd = fds[1];
read_info.bytes_read = 0;
pthread_t read_thread;
ASSERT_EQ(0, pthread_create(&read_thread, nullptr, reader, &read_info));
size_t write_count = 0;
while (write_count < write_size) {
size_t to_send = write_size - write_count;
ssize_t bytes_read = write(fds[0], send_mem + write_count, to_send);
ASSERT_LT(-1, bytes_read);
write_count += bytes_read;
}
ASSERT_EQ(0, pthread_join(read_thread, nullptr));
close(fds[0]);
close(fds[1]);
ASSERT_EQ(write_count, read_info.bytes_read);
ASSERT_EQ(0, memcmp(send_mem, read_info.mem, sizeof(unsigned char) * write_size));
delete[] send_mem;
delete[] read_info.mem;
}
TEST(UnixSocket, ImmediatePeercredCheck) {
char* tmp = getenv("TEST_TMPDIR");
std::string path = tmp == nullptr ? "/tmp/socktest" : std::string(tmp) + "/socktest";
struct sockaddr_un sun;
sun.sun_family = AF_UNIX;
strcpy(sun.sun_path, path.c_str());
struct sockaddr* addr = reinterpret_cast<struct sockaddr*>(&sun);
int server = socket(AF_UNIX, SOCK_STREAM, 0);
ASSERT_GT(server, -1);
ASSERT_EQ(bind(server, addr, sizeof(sun)), 0);
ASSERT_EQ(listen(server, 1), 0);
int client = socket(AF_UNIX, SOCK_STREAM, 0);
ASSERT_GT(client, -1);
ASSERT_EQ(connect(client, addr, sizeof(sun)), 0);
struct ucred cred;
socklen_t cred_size = sizeof(cred);
ASSERT_EQ(getsockopt(client, SOL_SOCKET, SO_PEERCRED, &cred, &cred_size), 0);
ASSERT_NE(cred.pid, 0);
ASSERT_NE(cred.uid, static_cast<uid_t>(-1));
ASSERT_NE(cred.uid, static_cast<gid_t>(-1));
}
TEST(UnixSocket, SendZeroFds) {
int fds[2];
ASSERT_EQ(0, socketpair(AF_UNIX, SOCK_STREAM, 0, fds));
char data[] = "a";
struct iovec iov[] = {{
.iov_base = data,
.iov_len = 1,
}};
char buf[CMSG_SPACE(0)];
struct msghdr msg = {
.msg_iov = iov,
.msg_iovlen = 1,
.msg_control = buf,
.msg_controllen = sizeof(buf),
};
*CMSG_FIRSTHDR(&msg) = (struct cmsghdr){
.cmsg_len = CMSG_LEN(0),
.cmsg_level = SOL_SOCKET,
.cmsg_type = SCM_RIGHTS,
};
ASSERT_EQ(sendmsg(fds[0], &msg, 0), 1);
memset(data, 0, sizeof(data));
memset(buf, 0, sizeof(buf));
ASSERT_EQ(recvmsg(fds[1], &msg, 0), 1);
EXPECT_EQ(data[0], 'a');
EXPECT_EQ(msg.msg_controllen, 0u);
}
|
3a845ca4559a772b1b18626698a6d656d17a9e56
|
0eff74b05b60098333ad66cf801bdd93becc9ea4
|
/second/download/CMake/CMake-gumtree/Kitware_CMake_repos_basic_block_block_18884.cpp
|
2f70803e7601a6b2eaa89bd1cc51f11b46860af7
|
[] |
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
| 63
|
cpp
|
Kitware_CMake_repos_basic_block_block_18884.cpp
|
(i = 0; i < count; i++) {
uv__free(cpu_infos[i].model);
}
|
c34fcd5dc1b79b45515a3f78fbb9e1be5a8a49e5
|
fdafc70a732badc2b32cad9b059925cd2591a3ec
|
/MetadataCopy/MetadataCopy/register.cpp
|
a45e3d95dbdcb98ad5ca74050a27337952ec8e88
|
[] |
no_license
|
RobinZhouAu/weilai
|
de11b121993b287f5b4cecccff4110eee3cc7dd5
|
ea6ec3d8f0a18fb901b457eb05dffcac4f327830
|
refs/heads/master
| 2021-03-22T00:12:29.390226
| 2016-11-05T11:21:40
| 2016-11-05T11:21:40
| 64,991,818
| 0
| 0
| null | null | null | null |
GB18030
|
C++
| false
| false
| 4,202
|
cpp
|
register.cpp
|
// Register.cpp: implementation of the CRegister class.
//
//////////////////////////////////////////////////////////////////////
#include "stdafx.h"
#include "search.h"
#include "Register.h"
#ifdef _DEBUG
#undef THIS_FILE
static char THIS_FILE[]=__FILE__;
#define new DEBUG_NEW
#endif
//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////
/*
only for string type;
//writer reg:
CRegister reg;
reg.CreateKey(HKEY_CURRENT_USER,_T("Software\\Dayang\\CDSearch\\Login"));
reg.SetString(_T("Name"), (LPCTSTR)m_strName);
reg.SetString(_T("Server"), (LPCTSTR)m_strSvr);
reg.CloseKey();
//read reg:
CRegister reg;
reg.OpenKey(HKEY_CURRENT_USER,_T("Software\\Dayang\\CDSearch\\Login"));
m_strSvr = reg.GetString(_T("Server"));
m_strName = reg.GetString(_T("Name"));
reg.CloseKey();
*/
CRegister::CRegister()
{
m_hKey = 0;
}
CRegister::~CRegister()
{
}
BOOL CRegister::CreateKey(HKEY hKey, LPCTSTR lpszSubKey)
{
if(RegCreateKey(hKey, lpszSubKey, &m_hKey) != ERROR_SUCCESS)
{
m_hKey = 0;
return FALSE;
}
return TRUE;
}
BOOL CRegister::DeleteValue(LPCTSTR lpszSubKey)
{
if(RegDeleteValue(m_hKey, lpszSubKey) != ERROR_SUCCESS)
{
return FALSE;
}
return TRUE;
}
BOOL CRegister::SetString(LPCTSTR lpszItem, LPCTSTR lpszValue)
{
LPBYTE pBuf;
int nBufSize;
pBuf = (LPBYTE)lpszValue;
nBufSize = _tcslen(lpszValue) * 2;
if(RegSetValueEx(m_hKey, lpszItem, 0, REG_SZ, pBuf, nBufSize) != ERROR_SUCCESS)
return FALSE;
return TRUE;
}
CString CRegister::GetString(LPCTSTR lpszItem, int nLength)
{
DWORD dwBufLen = 40960;
CString strValue;
BYTE pBuf[40960];
memset(pBuf,0,40960);
DWORD dwType = REG_SZ;
if(RegQueryValueEx(m_hKey, lpszItem, NULL, &dwType, pBuf, &dwBufLen) != ERROR_SUCCESS)
return _T("");
strValue = (TCHAR *)pBuf;
return strValue;
}
BOOL CRegister::GetString(LPCTSTR lpszItem, CString &strValue, int nLength)
{
DWORD dwBufLen = 40960;
BYTE pBuf[40960];
memset(pBuf,0,40960);
DWORD dwType = REG_SZ;
if(RegQueryValueEx(m_hKey, lpszItem, NULL, &dwType, pBuf, &dwBufLen) != ERROR_SUCCESS)
return FALSE;
strValue = (TCHAR *)pBuf;
return TRUE;
}
BOOL CRegister::GetDWord(LPCTSTR lpszItem, DWORD &dwValue)
{
DWORD dwType = REG_DWORD;
DWORD dwSize = 4;
if(RegQueryValueEx(m_hKey, lpszItem, NULL, &dwType, (BYTE *)&dwValue, &dwSize) != ERROR_SUCCESS)
return FALSE;
return TRUE;
}
BOOL CRegister::CloseKey()
{
RegCloseKey(m_hKey);
m_hKey = 0;
return TRUE;
}
BOOL CRegister::OpenKey(HKEY hKey, LPCTSTR lpszSubKey)
{
LSTATUS status = RegOpenKeyEx(hKey, lpszSubKey, 0, KEY_ALL_ACCESS, &m_hKey);
if(status != ERROR_SUCCESS)
{
m_hKey = 0;
return FALSE;
}
return TRUE;
}
BOOL CRegister::SetDWord(LPCTSTR lpszItem, DWORD dwValue)
{
LONG lRet = RegSetValueEx(m_hKey, lpszItem, 0, REG_DWORD, (const BYTE *)&dwValue, 4);
if(lRet != ERROR_SUCCESS)
return FALSE;
return TRUE;
}
BOOL CRegister::EnumValue(CArrayRegValue& arrRegValue)
{
LONG LRet;
DWORD dwIndex = 0;
DWORD dwNameSize = 40960;
DWORD dwBufLen = 40960;
DWORD dwType = REG_SZ;
BYTE pBufValue[40960];
//memset(pBufValue,0,1024);
TCHAR pBufName[40960];
//memset(pBufName,0,1024*sizeof(TCHAR));
for (int i = 0; i < arrRegValue.GetSize(); i++)
delete arrRegValue[i];
arrRegValue.RemoveAll();
while(LRet = RegEnumValue(m_hKey, dwIndex, pBufName, &dwNameSize, NULL, &dwType, pBufValue, &dwBufLen) != ERROR_NO_MORE_ITEMS)
{
PTR_ENUM_REG_VALUE pRegValue = new ENUM_REG_VALUE;
pRegValue->strName = (TCHAR *)pBufName;
if ((dwType == REG_SZ || dwType == REG_DWORD) && pRegValue->strName != _T("") )//去掉注册表中的默认选项
pRegValue->enumType = dwType;
else
{
TRACE(_T("UnSupport RegType!") );
delete pRegValue;
dwIndex++;
dwNameSize = 40960;
dwBufLen = 40960;
continue;
}
switch (pRegValue->enumType)
{
case REG_SZ:
pRegValue->strValue = (TCHAR *)pBufValue;
break;
case REG_DWORD:
pRegValue->dwValue = *(DWORD *)pBufValue;
break;
}
arrRegValue.Add(pRegValue);
dwIndex++;
dwNameSize = 40960;
dwBufLen = 40960;
}
if (LRet != ERROR_SUCCESS)
return FALSE;
return TRUE;
}
|
b9f6ae706346a28eb2386bcbd7fe5362337a739f
|
2c811434dd9cc3bb54d64f92733c40ddd3fa0383
|
/UVa-AC/uva 341 Non-stop Travel.cpp
|
344c45bef7e73da4bd894d3ed1abd12ef2d67327
|
[] |
no_license
|
gmtranthanhtu/competitive-programming
|
457e5cc16ede75d9496ac195de845ebe8d6e5664
|
d765002704e2a8cf547cbe67f0f9a31db88bfc9b
|
refs/heads/master
| 2021-01-23T08:56:52.594506
| 2014-11-01T09:52:12
| 2014-11-01T09:52:12
| 26,047,176
| 3
| 3
| null | 2020-10-01T14:15:30
| 2014-11-01T09:55:03
|
C++
|
UTF-8
|
C++
| false
| false
| 3,463
|
cpp
|
uva 341 Non-stop Travel.cpp
|
/*
Name: UVa 341 Non-Stop Travel
Copyright:
Author: 3T
Date: 31/05/11 00:08
Description: graph, dijsktra
*/
#include <stdio.h>
#include <string.h>
#include <iostream>
#include <algorithm>
using namespace std;
#define MAX 50
#define BIG 99999999
int Case(0), N, n, a, b, S, E, p, C[MAX][MAX], d[MAX], Trace[MAX], Path[MAX];
bool Free[MAX];
void Config(){
for(int i = 1; i <= N; i++){
Free[i] = true;
d[i] = BIG;
for(int j = 1; j <= N; j++){
C[i][j] = BIG;
}
}
}
void Dijsktra(){
d[S] = 0;
int u, Min;
do{
u = 0;
Min = BIG;
for(int i = 1; i <= N; i++){
if(Free[i] && d[i] < Min){
u = i;
Min = d[i];
}
}
if(u == 0 || u == E) break;
Free[u] = false;
for(int i = 1; i <= N; i++){
if(Free[i] && d[i] > d[u] + C[u][i]){
d[i] = d[u] + C[u][i];
Trace[i] = u;
}
}
} while(1);
}
void findPath(){
p = 0;
p++;
Path[p] = E;
int Tmp = Trace[E];
while(Tmp != S){
p++;
Path[p] = Tmp;
Tmp = Trace[Tmp];
}
p++;
Path[p] = S;
}
void Print(){
Case++;
printf("Case %d: Path = ",Case);
for(int i = p; i >= 1; i--){
if(i == p) printf("%d",Path[i]);
else
printf(" %d",Path[i]);
}
printf("; %d second delay\n",d[E]);
}
int main () {
//freopen("341.INP", "r", stdin); freopen("341.OUT", "w", stdout);
while(scanf("%d",&N) && N){
//config
Config();
for(int i = 1; i <= N; i++){
scanf("%d",&n);
for(int j = 1; j <= n; j++){
scanf("%d%d",&a,&b);
C[i][a] = b;
}
}
scanf("%d%d",&S,&E);
//process
Dijsktra();
findPath();
Print();
//print("Case %d: Path = ", i);
}
return 0;
}
|
234850928c114c5f41f58c4d36a6ec66c5ce9e03
|
151bcfc3cab30d635f1d048c80ca7f0332db3b9d
|
/common/resource.cpp
|
e158a40926a46714f6687d8d4e43ba9f453f51a0
|
[] |
no_license
|
alinelena/sink
|
1c3928d1f8d48b24df6354a6ef3f70fffb03024a
|
cbb192ffe865ffb3eed4c940177ffecaecfa570f
|
refs/heads/master
| 2021-01-15T10:36:06.801649
| 2015-02-09T11:58:34
| 2015-02-09T11:58:34
| 65,147,167
| 0
| 0
| null | 2016-08-07T18:09:21
| 2016-08-07T18:09:20
| null |
UTF-8
|
C++
| false
| false
| 4,202
|
cpp
|
resource.cpp
|
/*
* Copyright (C) 2014 Aaron Seigo <aseigo@kde.org>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) version 3, or any
* later version accepted by the membership of KDE e.V. (or its
* successor approved by the membership of KDE e.V.), which shall
* act as a proxy defined in Section 6 of version 3 of the license.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library. If not, see <http://www.gnu.org/licenses/>.
*/
#include "resource.h"
#include <QCoreApplication>
#include <QDir>
#include <QPluginLoader>
#include <QPointer>
namespace Akonadi2
{
Resource::Resource()
: d(0)
{
}
Resource::~Resource()
{
//delete d;
}
void Resource::configurePipeline(Pipeline *pipeline)
{
}
void Resource::processCommand(int commandId, const QByteArray &data, uint size, Pipeline *pipeline)
{
Q_UNUSED(commandId)
Q_UNUSED(data)
Q_UNUSED(size)
Q_UNUSED(pipeline)
pipeline->null();
}
Async::Job<void> Resource::synchronizeWithSource(Pipeline *pipeline)
{
return Async::start<void>([pipeline](Async::Future<void> &f) {
pipeline->null();
});
}
Async::Job<void> Resource::processAllMessages()
{
return Async::null<void>();
}
class ResourceFactory::Private
{
public:
static QHash<QString, QPointer<ResourceFactory> > s_loadedFactories;
};
QHash<QString, QPointer<ResourceFactory> > ResourceFactory::Private::s_loadedFactories;
ResourceFactory::ResourceFactory(QObject *parent)
: QObject(parent),
d(0)
{
}
ResourceFactory::~ResourceFactory()
{
//delete d;
}
ResourceFactory *ResourceFactory::load(const QString &resourceName)
{
ResourceFactory *factory = Private::s_loadedFactories.value(resourceName);
if (factory) {
return factory;
}
for (auto const &path: QCoreApplication::instance()->libraryPaths()) {
if (path.endsWith(QLatin1String("plugins"))) {
QDir pluginDir(path);
//TODO: centralize this so that it is easy to change centrally
// also ref'd in cmake as ${AKONADI_RESOURCE_PLUGINS_PATH}
pluginDir.cd(QStringLiteral("akonadi2"));
pluginDir.cd(QStringLiteral("resources"));
for (const QString &fileName: pluginDir.entryList(QDir::Files)) {
const QString path = pluginDir.absoluteFilePath(fileName);
QPluginLoader loader(path);
const QString id = loader.metaData()[QStringLiteral("IID")].toString();
if (id == resourceName) {
QObject *object = loader.instance();
if (object) {
factory = qobject_cast<ResourceFactory *>(object);
if (factory) {
Private::s_loadedFactories.insert(resourceName, factory);
factory->registerFacades(FacadeFactory::instance());
//TODO: if we need more data on it const QJsonObject json = loader.metaData()[QStringLiteral("MetaData")].toObject();
return factory;
} else {
qWarning() << "Plugin for" << resourceName << "from plugin" << loader.fileName() << "produced the wrong object type:" << object;
delete object;
}
} else {
qWarning() << "Could not load factory for" << resourceName << "from plugin" << loader.fileName() << "due to the following error:" << loader.errorString();
}
}
}
}
}
qWarning() << "Failed to find factory for resource:" << resourceName;
return nullptr;
}
} // namespace Akonadi2
|
286940fb4b86d8880141d5de4f393d5e8e684d51
|
6637c6eeed6044338f45d86a3ee8843961de0c43
|
/avaliacao1_vitor_emanuel/conta_corrente.h
|
8d529760b21f9c1bdd7b6eff2acd5c203ef76aa6
|
[] |
no_license
|
vitoremanuelpereirasilva/INF112
|
147c9ac5d418f0d05e2878ee211b930497e28e32
|
d4ed69bd4d3ecd7edf9f8ad227fa52f5e234bde6
|
refs/heads/main
| 2023-05-06T04:36:22.813233
| 2021-06-01T22:49:42
| 2021-06-01T22:49:42
| 372,979,701
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 230
|
h
|
conta_corrente.h
|
#ifndef CONTA_CORRENTE_H
#define CONTA_CORRENTE_H
#include <string>
#include "conta.h"
class contacorrente : public conta{
private:
public:
contacorrente(std::string name,std::string cpf, double saldo);
};
#endif
|
e72dccc343981edfd607874f526aeeb97f78152e
|
0c4afe621423b8d3c6b0a551f16e5f72f2725aa0
|
/prob6.cpp
|
f0be91deb6a2d99a926d0a6909afa6361172f5a4
|
[] |
no_license
|
jenil123/competitive_coding
|
2c7b110174d993d8cb0c7a031304e9911510e6ab
|
ea66244a5e4f34ae7ea34e963733de0546b289ea
|
refs/heads/master
| 2022-12-04T16:46:52.502875
| 2020-08-24T05:22:36
| 2020-08-24T05:22:36
| 115,807,725
| 2
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 984
|
cpp
|
prob6.cpp
|
#include <bits/stdc++.h>
#define ll long long int
using namespace std;
int main()
{
int t;
cin>>t;
while(t--)
{
vector <ll> a(3);
vector <ll> c(3);
ll i,j;
for(i=0;i<3;i++)
{
cin>>a[i];
}
for(i=0;i<3;i++)
{
cin>>c[i];
}
ll count=0;
if(a[0]>a[1]&&c[0]>c[1])
count++;
else if(a[0]<a[1]&&c[0]<c[1])
count++;
else if(a[0]==a[1]&&c[0]==c[1])
count++;
else{}
if(a[1]>a[2]&&c[1]>c[2])
count++;
else if(a[1]<a[2]&&c[1]<c[2])
count++;
else if(a[1]==a[2]&&c[1]==c[2])
count++;
else{}
if(a[0]>a[2]&&c[0]>c[2])
count++;
else if(a[0]<a[2]&&c[0]<c[2])
count++;
else if(a[0]==a[2]&&c[0]==c[2])
count++;
else{}
if(count==3)
cout<<"FAIR"<<endl;
else
cout<<"NOT FAIR"<<endl;
}
}
|
fbf1c79ef3082d6bed075ef464518bc2f58d970e
|
d6b0c51999cecf65d5be208fab74bb8a199eb0ac
|
/MagicCube/Manipulation.h
|
efb5c2fefa44d032be710cd11fcdaeba6542c41a
|
[] |
no_license
|
k-l-lambda/klsmagiccube
|
5076e6be0a729ff8741d960e44e5fb061c473b08
|
1cfb166f537573b7e64d902085075ff0e99b9166
|
refs/heads/master
| 2016-09-05T22:12:35.513552
| 2011-02-10T16:17:38
| 2011-02-10T16:17:38
| 32,123,748
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 398
|
h
|
Manipulation.h
|
/*
** This source file is part of K.L.'s MagicCube.
**
** Copyright (c) 2008 K.L.<xxxk.l.xxx@gmail.com>
** This program is free software without any warranty.
*/
#ifndef __MANIPULATION_H__
#define __MANIPULATION_H__
namespace MagicCube
{
struct UnitCube;
enum Manipulation;
void manipulation(UnitCube& uc, Manipulation m);
}
#endif // !defined(__MANIPULATION_H__)
|
c7f14d312fec9f630d10b112031059d2cea97087
|
a3d6556180e74af7b555f8d47d3fea55b94bcbda
|
/chrome/browser/ash/system_extensions/system_extensions_internals_page_handler.cc
|
2a3adea4deedc9b0d4796ea144c76db27e0f4f57
|
[
"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
| 3,111
|
cc
|
system_extensions_internals_page_handler.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/ash/system_extensions/system_extensions_internals_page_handler.h"
#include "base/debug/stack_trace.h"
#include "base/functional/callback_helpers.h"
#include "base/system/sys_info.h"
#include "chrome/browser/ash/system_extensions/system_extensions_profile_utils.h"
namespace ash {
SystemExtensionsInternalsPageHandler::SystemExtensionsInternalsPageHandler(
Profile* profile,
mojo::PendingReceiver<mojom::system_extensions_internals::PageHandler>
receiver)
: profile_(profile), receiver_(this, std::move(receiver)) {}
SystemExtensionsInternalsPageHandler::~SystemExtensionsInternalsPageHandler() =
default;
void SystemExtensionsInternalsPageHandler::
InstallSystemExtensionFromDownloadsDir(
const base::SafeBaseName& system_extension_dir_name,
InstallSystemExtensionFromDownloadsDirCallback callback) {
if (!IsSystemExtensionsEnabled(profile_)) {
std::move(callback).Run(false);
return;
}
base::FilePath downloads_path;
// Return a different path when we are running ChromeOS on Linux, where the
// Downloads folder is different than on a real device. This is to make
// development on ChromeOS on Linux easier.
auto path_enum = base::SysInfo::IsRunningOnChromeOS()
? chrome::DIR_DEFAULT_DOWNLOADS_SAFE
: chrome::DIR_DEFAULT_DOWNLOADS;
if (!base::PathService::Get(path_enum, &downloads_path)) {
std::move(callback).Run(false);
return;
}
auto& install_manager =
SystemExtensionsProvider::Get(profile_).install_manager();
base::FilePath system_extension_dir =
downloads_path.Append(system_extension_dir_name);
install_manager.InstallUnpackedExtensionFromDir(
system_extension_dir,
base::BindOnce(&SystemExtensionsInternalsPageHandler::OnInstallFinished,
weak_ptr_factory_.GetWeakPtr(), std::move(callback)));
}
void SystemExtensionsInternalsPageHandler::IsSystemExtensionInstalled(
IsSystemExtensionInstalledCallback callback) {
auto& registry = SystemExtensionsProvider::Get(profile_).registry();
const bool is_installed = !registry.GetIds().empty();
std::move(callback).Run(is_installed);
}
void SystemExtensionsInternalsPageHandler::UninstallSystemExtension(
UninstallSystemExtensionCallback callback) {
auto scoped_callback_runner = base::ScopedClosureRunner(std::move(callback));
auto& provider = SystemExtensionsProvider::Get(profile_);
auto& registry = provider.registry();
const auto ids = registry.GetIds();
if (ids.empty())
return;
provider.install_manager().Uninstall(ids[0]);
}
void SystemExtensionsInternalsPageHandler::OnInstallFinished(
InstallSystemExtensionFromDownloadsDirCallback callback,
InstallStatusOrSystemExtensionId result) {
if (!result.ok()) {
LOG(ERROR) << "failed with: " << static_cast<int32_t>(result.status());
}
std::move(callback).Run(result.ok());
}
} // namespace ash
|
574394fb0eeab21519fa014e162083eed8f92dbb
|
df82d249dbab2a47ca4fbee5cde7482aac482949
|
/fall2013/cop3530/ass_2/main (copy).cpp
|
33fcdc95aa2b7ed229feb0809ede0571fa6334c2
|
[] |
no_license
|
makslevental/school_work
|
e0ee01f008cb3afda14d11befa74ed8023949a55
|
982a874366eba361f0205b5e55d80dda3b564c92
|
refs/heads/master
| 2021-06-01T22:42:31.598338
| 2021-05-29T20:45:45
| 2021-05-29T20:45:45
| 16,900,294
| 1
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 4,280
|
cpp
|
main (copy).cpp
|
/*
Name: Maksim Levental
UF ID: 3186-7826
Gator ID: mlevental86
Discussion Section #: 1085
*/
#include <iostream> // necessary for cout, string, isdigit
#include <ostream>
#include <sstream> // necessary for stringstream
#include <cstdlib> // necessary for exit()
#include <locale> // locale, tolower
#include "ArrayLinearList.h"
using namespace std;
// data validation method. prevents arguments that aren't a choice or 'q' from being passed to switch in main
char alpha_sanitize(){
char entry = '\0';
while(1){
cout << "\nPick a task to perform please by entering the letter in brackets\n\n";
cout << "[I]nsert an element\n";
cout << "[D]elete an element\n";
cout << "[P]rint out the entire List\n";
cout << "Print the Current [S]ize List\n";
cout << "Print Particular [E]lement\n";
cout << "Print the [M]aximum and the [M]inimum elements in the list\n";
cout << "[Q]uit\n\n";
cin >> entry;
entry = tolower(entry);
system("clear");
if(entry != 'c' && entry != 'e' && entry != 'i' && entry != 'd' && entry != 'p' && entry != 's' && entry != 'q' && entry != 'm') { cout << "\nError, Invalid entry\n"; continue; }
if(entry == 'q') exit(0);
break;
}
return(entry);
}
int num_sanitize(){
string entry;
loop:
while(1){
cout << "\nEnter the capacity you would like to initialize the list (or enter ‘q’ to quit): ";
// static declaration so that later *sanitized can point to it after method returns
cin >> entry;
if(entry == "q") exit(0);
for(int i = 0; i < entry.length(); i++){
// walk through array entry and search for element that !isdigit. if !isdigit then set *sanitized to NULL pointer
// and return from method. if every element isdigit then conditional is not activated and for loop exits normally
if(!isdigit(entry[i])){ cout << "\nInvalid entry, please try again\n\n"; goto loop;}
}
break;
}
// if for loop finishes normally then set *sanitized to point to string entry and return
stringstream actual_entry;
long long int n;
actual_entry << entry;
actual_entry >> n;
return(n);
}
int main()
{
arrayList<int> bobs(num_sanitize());
int element = 0, index = 0;
for(int i = 0; i < bobs.capacity(); i++){
bobs.insert(i,i);
}
while(1){
switch(alpha_sanitize()){
case 'i':
system("clear");
while(1) {
cout << "\nPlease enter element to insert: ";
if(cin >> element) break;
else{
cout << "\nError: Please enter a valid integer\n" ;
cin.clear();
cin.ignore(10000,'\n');
}
}
while(1){
cout << "\nPlease enter index to insert at: ";
if(cin >> index) break;
else{
cout << "\nError: Please enter a valid integer\n" << endl;
cin.clear();
cin.ignore(10000,'\n');
}
}
try{ bobs.insert(index, element); }
catch(...){ cout << ARRAY_ERROR; }
break;
case 'd':
system("clear");
while(1) {
cout << "\nPlease enter index to delete at: ";
if (cin >> index) break;
else{
cout << "\nError: Please enter a valid integer\n" << endl; //array bounds!!!!!!!!!!!!!!!!!
cin.clear();
cin.ignore(10000,'\n');
}
}
try{ bobs.erase(index); }
catch(...){ cout << ARRAY_ERROR; }
break;
case 'p':
system("clear");
cout << bobs << endl;
break;
case 's':
system("clear");
bobs.print_current_size();
break;
case 'm':
system("clear");
bobs.print_min_max();
break;
case 'e':
system("clear");
while(1){
cout << "\nPlease enter index: ";
if(cin >> index) break;
else{
cout << "\nError: Please enter a valid integer\n" << endl;
cin.clear();
cin.ignore(10000,'\n');
}
}
try{ cout << endl << bobs[index] << endl; }
catch(...){ cout << ARRAY_ERROR; }
break;
case 'c': // super secret debugging case
cout << bobs.capacity();
cout << endl << endl;
bobs.print_array();
}
}
}
|
5a519eb9943ff86087dea1ae978623c9aa994406
|
6e61611828817438b452dbcf518d0f78e7e89115
|
/数组.cpp
|
bbbcd5fef8291647c7772da5eb9f5f04528947f0
|
[] |
no_license
|
fsp-ending/OJ
|
2c395e6653ac5ac73f25d6f46e2df27d2655ac20
|
1f95b4cb93061ace53e5092c97affeb8815e1d79
|
refs/heads/master
| 2022-07-13T06:21:09.178126
| 2020-05-18T22:23:01
| 2020-05-18T22:23:01
| 260,235,240
| 2
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 991
|
cpp
|
数组.cpp
|
/*************************************************************************
> File Name: 数组.cpp
> Author:
> Mail:
> Created Time: 2020年05月10日 星期日 20时10分49秒
************************************************************************/
#include<iostream>
#include<cstdio>
using namespace std;
void func(int *a) {
printf("&a = %p\n", a);
printf("*a = %d\n", *a);
char *p;
printf("&a = %d\n", *a);
printf("p = %p, p + 1 = %p\n", p, p + 1);
return ;
}
void func2(int (*b)[9]) {
printf("b = %p, b + 1 = %p\n", b, b + 1);
return ;
}
void func3() {
int **c;
printf("c = %p, c + 1 = %p\n", c , c + 1);
}
int main() {
int arr[100] = { 1, 2, 3 };
char str[10] = { 0 };
int arr2[4][9];
printf("arr = %p, arr[1] = %p\n", arr, &arr[1]);
printf("str = %p, str[1] = %p\n", str, &str[1]);
int n;
printf("arr2 = %p, arr2 + 1 = %p\n", arr2, arr2 + 1);
func(arr);
func2(arr2);
func3();
return 0;
}
|
95fc35cf9b02bd7be44aee748e1627949e5aa49a
|
9be573b87220a3f9c02f17b987b16dc90ac6b048
|
/keshe/train/deletetrain.h
|
1cceb849ec7061710dd5b4ee0e729e246381e5fc
|
[] |
no_license
|
shuai1126/keshe
|
c72aeae176aa947f49a2a3fe8778acabbe10a365
|
fab075306412c645a5746b8812db26608b055a54
|
refs/heads/master
| 2020-03-22T10:42:50.991682
| 2018-07-13T01:30:18
| 2018-07-13T01:30:18
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 442
|
h
|
deletetrain.h
|
#ifndef DELETETRAIN_H
#define DELETETRAIN_H
#include <QSqlDatabase>
#include <QDebug>
#include <QtSql>
#include <QMessageBox>
namespace Ui {
class DeleteTrain;
}
class DeleteTrain : public QWidget
{
Q_OBJECT
public:
explicit DeleteTrain(QWidget *parent = 0);
~DeleteTrain();
private slots:
void on_pushButton_clicked();
void on_pushButton_2_clicked();
private:
Ui::DeleteTrain *ui;
};
#endif // DELETETRAIN_H
|
c74842726dd07081d0628a0617f1882e83add7e3
|
e508fa70f2c1fa69e2a30abf28dffd158acbdeca
|
/BST/BSTC++Style.cpp
|
6a70fe70ea03cb6f7ad29241f7a5805083e112a7
|
[] |
no_license
|
ShahPranav1094-Courses/Algorithms-DataStructures
|
2f35e9ccc1dd22ba0b1a57ce5e1df60f62876c17
|
6243bd0c8f40eb89f99255d54e13e884dc5e4f88
|
refs/heads/master
| 2020-07-27T08:29:00.261022
| 2020-04-25T11:21:46
| 2020-04-25T11:21:46
| 209,030,183
| 0
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 4,995
|
cpp
|
BSTC++Style.cpp
|
/* ------------------------------------------------------------------------------------
Node Header (Node.hxx)
------------------------------------------------------------------------------------ */
#include <iostream>
using namespace std;
/* Class Node */
class Node
{
public:
int data; // Data to be stored
Node* left; // Pointer to left child
Node* right; // Pointer to right child
};
/* ------------------------------------------------------------------------------------
BSTree Header (BSTree.hxx)
------------------------------------------------------------------------------------ */
#include "Node.hxx"
/* Class BSTree */
class BSTree
{
public:
// Default Constructor
BSTree();
// Insert in Binary Search Tree Recursively
Node* InsertRec(Node* root, int key);
// Insert in Binary Search Tree Iteratively
Node* InsertItr(Node* root, int key);
// Display BSTree Using InOrder
void InOrder(Node* root);
// Search a key in Binary Search Tree Iteratively
bool SearchItr(Node* root, int key);
// Search a key in Binary Search Tree Recursively
bool SearchRec(Node* root, int key);
// Destructor
~BSTree();
};
/* ------------------------------------------------------------------------------------
BSTree Implementation (BSTree.cxx)
------------------------------------------------------------------------------------ */
#include "BSTree.hxx"
/* ----------------------------------- */
BSTree::BSTree()
{
}
/* ----------------------------------- */
Node* BSTree::InsertRec(Node* t, int key)
{
if (t == nullptr)
{
Node* temp = new Node;
temp->left = temp->right = nullptr;
temp->data = key;
return temp;
}
if (key < t->data)
t->left = InsertRec(t->left, key);
else if (key > t->data)
t->right = InsertRec(t->right, key);
return t;
}
/* ----------------------------------- */
Node* BSTree::InsertItr(Node* root, int key)
{
Node* tail = nullptr;
if (root == nullptr)
{
Node* temp = new Node;
temp->left = temp->right = nullptr;
temp->data = key;
return temp;
}
while (root != nullptr)
{
tail = root;
if (key == root->data)
return nullptr;
else if (key < root->data)
root = root->left;
else
root = root->right;
}
Node* temp = new Node;
temp->left = temp->right = nullptr;
temp->data = key;
if (key < tail->data)
tail->left = temp;
else
tail->right = temp;
return temp;
}
/* ----------------------------------- */
void BSTree::InOrder(Node * root)
{
if (root == nullptr)
return;
InOrder(root->left);
cout << root->data << " ";
InOrder(root->right);
}
/* ----------------------------------- */
bool BSTree::SearchItr(Node * root, int key)
{
if (root == nullptr)
return false;
Node * tail = nullptr;
while (root != nullptr)
{
if (root->data == key)
return true;
else if (key < root->data)
root = root->left;
else
root = root->right;
}
return false;
}
/* ----------------------------------- */
bool BSTree::SearchRec(Node * root, int key)
{
if (root == nullptr)
return false;
if (key == root->data)
return true;
else if (key < root->data)
return SearchRec(root->left, key);
else
return SearchRec(root->right, key);
}
/* ----------------------------------- */
BSTree::~BSTree()
{
}
/* ------------------------------------------------------------------------------------
Main CPP File (Source.cpp)
------------------------------------------------------------------------------------ */
#include "BSTree.hxx"
/* Main Method */
int main()
{
BSTree t;
Node* root = nullptr;
root = t.InsertRec(root, 7);
t.InsertRec(root, 3);
t.InsertRec(root, 10);
t.InsertRec(root, 1);
t.InsertRec(root, 4);
t.InsertRec(root, 8);
t.InsertRec(root, 12);
cout << "The Inorder Traversal of Binary Search Tree is : ";
t.InOrder(root);
cout << endl << endl;
cout << "Is node 4 found using Iterative Search ? " << boolalpha << t.SearchItr(root, 4) << endl << endl;
cout << "Is node 4 found using Recursive Search ? " << boolalpha << t.SearchRec(root, 4) << endl << endl;
cout << "Is node 14 found using Iterative Search ? " << boolalpha << t.SearchItr(root, 14) << endl << endl;
cout << "Is node 14 found using Recursive Search ? " << boolalpha << t.SearchRec(root, 14) << endl << endl;
system("pause");
return 0;
}
/*
Output
The Inorder Traversal of Binary Search Tree is : 1 3 4 7 8 10 12
Is node 4 found using Iterative Search ? true
Is node 4 found using Recursive Search ? true
Is node 14 found using Iterative Search ? false
Is node 14 found using Recursive Search ? false
*/
|
fc1016363b19147778db8d85b598f3a2b1ebe398
|
017ac0d879d635947aaa2b12f6594881a85cfee8
|
/main.cpp
|
306858fe5052735da059e2600c771bb4ee893816
|
[] |
no_license
|
Amey-Jain/OOP-gst_calc
|
b2859d1aa8a0c5fcec8e2fcde89e30dee8dbd347
|
f08ba9341db9b6ffa9d4caa47fad6fb149b4bbbf
|
refs/heads/master
| 2020-03-25T15:54:43.380333
| 2018-08-14T11:27:53
| 2018-08-14T11:27:53
| 143,906,688
| 0
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 4,062
|
cpp
|
main.cpp
|
#include <iostream>
#include <string>
#include <cassert>
#include <cstring>
#include <bits/stdc++.h>
#include <cstdlib>
#include <list>
#include "db.h"
#include "product.h"
using namespace std;
// class to hold all of items
class ilist {
public:
ilist();
int enter_item(string item_name, double item_units); //takes input of an item name and checks if it exists in existing database or not
void print_items();
void print_gst_invoice();
private:
list <product> items;
product *p_list;
int prod_count;
};
// initializes the p_list, parses and stores all
// values from db file into its objects
ilist::ilist(){
string data, line;
data = load_db(prod_count);
if(prod_count <= 0)
cerr << "Error: Negative/Zero products to initialize\n" ;
stringstream str(data);
int ctr = 0;
//initialize product list
p_list = new product[prod_count];
//tokenize and store all product values inside
while(getline(str, line, '|')){
p_list[ctr].parse_and_store(line);
ctr++;
}
}
// Checks item name with each item in item_list. If a match is found, its index
// is returned back, else -1.
int ilist::enter_item(string item_name, double item_units){
int item_found = 0;
for(int i = 0;i < prod_count ; i++){
if(item_name.compare(p_list[i].get_name()) == 0){
//insert into items list
product p = product(p_list[i], item_units);
if(p.get_status() == 'o') // all ok
items.push_back(p);
if(p.get_status() == 'i') {
cerr << "Error: Item \'" << p.get_name() << "\' cannot have non-fractional quantities. Kindly re-enter product\n";
return -1;
}
item_found = 1;
return i;
}
}
if(item_found != 1){
cerr << "Error: Item name " << item_name << " not found in database\n";
return -1;
}
return 0;
}
void ilist::print_gst_invoice(){
list <product>::iterator ptr;
double gst_total = 0, gross_total = 0;
cout << "Name\t\tQuantity \tPrice\tGST Applicable\tTotal\n";
for(ptr = items.begin(); ptr != items.end(); ptr++){
double temp_gst = static_cast<double>(ptr->get_price() * ptr->get_quantity() * ptr->get_slab_rate() / 100);
cout << ptr->get_name() << "\t\t" << ptr->get_quantity() << " " << ptr->get_unit() << "\t\t"
<< ptr->get_price() << "\t" << temp_gst << "\t\t"
<< (ptr->get_price() * ptr->get_quantity()) + temp_gst << endl;
gst_total = gst_total + temp_gst;
gross_total = gross_total + (ptr->get_price() * ptr->get_quantity()) + temp_gst;
}
cout << "--------------------------------------------------------------------------\n";
cout << "\nGROSS \tTOTAL \t\t"<< gst_total <<" \t\t" << gross_total << "\n";
}
void ilist::print_items(){
for( int i = 0; i < prod_count; i++)
cout << p_list[i].get_name() << endl;
}
int main(int argc, char *argv[]){
//open and load db file
string data, line, token1, token2;
double quant_temp;
string item_temp;
ilist product_list;
if((argc < 2) || strcmp(argv[1],"--help") == 0){
cout << "How to use tool\n";
cout << "user:~/working/directory$:./main --run\n";
cout << "Enter the list of items and quantity saperated by space. Enter eol for indicating End of list\n";
cout << "rice 2.5\n"
<< "perfume 2\n"
<< "eol\n";
exit(1);
}
else if(argc > 2){
cout << "Undefined options. Exiting Try --help for help\n--run for running program\n";
exit(1);
}
else if(strcmp(argv[1],"--run") == 0){
cout << "Enter the list of items and quantity saperated by space. Enter eol for indicating End of list\n";
while(getline(cin, line, '\n')){
if(line.compare("eol") == 0)
break;
stringstream temp(line);
getline(temp, token1, ' ');
getline(temp, token2, ' ');
quant_temp = strtod(token2.c_str(), NULL);
if(quant_temp == 0) {
cerr << "Error: Enter item name and then quantity\n";
continue;
}
int i = product_list.enter_item(token1, quant_temp);
if(i < 0)
cerr << "Error: Unable to enter product\n";
}
product_list.print_gst_invoice();
}
return 0;
}
|
6380a052c323c3fcfc876bad30c44533d6b7c7bd
|
e09b3ccecaf599be9c0e2052d2bee6830864f472
|
/libgbstd/roll_menu.cpp
|
0422d3910bdd3ee9131870be6a813dce057a84a0
|
[] |
no_license
|
mugisaku/gamebaby-20180215-dumped
|
8811fa990b872e3118dd6fa0082e34db7df2861c
|
13845aab5d7f73744d72b41eb6090ec2a96de968
|
refs/heads/master
| 2021-09-07T01:03:45.120942
| 2018-02-14T15:32:17
| 2018-02-14T15:32:17
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,735
|
cpp
|
roll_menu.cpp
|
#include"libgbstd/menu.hpp"
namespace gbstd{
namespace menus{
roll_menu::
roll_menu(const menu_base& base, int col_n, int row_n, point pt) noexcept:
m_base(base),
m_number_of_columns(col_n),
m_number_of_rows(row_n)
{
window::resize(m_base.get_item_width()*m_number_of_columns+16,
m_base.get_image_height() +16);
set_base_point(pt);
}
void
roll_menu::
reset_cursor() noexcept
{
m_y_base = 0;
m_cursor = point();
}
void
roll_menu::
move_cursor_to_left() noexcept
{
if(m_cursor.x)
{
m_cursor.x -= 1;
}
}
void
roll_menu::
move_cursor_to_right() noexcept
{
if(m_cursor.x < (m_number_of_columns-1))
{
m_cursor.x += 1;
}
}
void
roll_menu::
move_cursor_to_up() noexcept
{
if(m_cursor.y){m_cursor.y -= 1;}
else if( m_y_base){m_y_base -= 1;}
}
void
roll_menu::
move_cursor_to_down() noexcept
{
const int y_base_end = (m_y_base+m_base.get_number_of_visible_rows());
if(m_cursor.y < (m_base.get_number_of_visible_rows()-1)){m_cursor.y += 1;}
else if(y_base_end < (m_number_of_rows -1)){m_y_base += 1;}
}
void
roll_menu::
render(image& dst, point offset) const noexcept
{
window::render(dst,offset);
if(window::get_state() == window_state::full_opened)
{
point const base_offset(get_base_point()+offset+8);
int w = m_base.get_item_width();
int h = m_base.get_item_height();
m_base.render(dst,base_offset,(m_number_of_columns*m_y_base),m_number_of_columns);
rectangle rect(base_offset.x+(w*m_cursor.x),
base_offset.y+(h*m_cursor.y),w,h);
dst.draw_rectangle(rect,pixel(predefined::yellow,30000));
}
}
}}
|
52dda380a3a9f76895c21cbde867417f3ef60601
|
0eff74b05b60098333ad66cf801bdd93becc9ea4
|
/second/download/httpd/gumtree/httpd_old_hunk_4841.cpp
|
b9719449a5905a39bf45f708534ab7d634a56553
|
[] |
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
| 359
|
cpp
|
httpd_old_hunk_4841.cpp
|
*/
apr_table_addn(r->headers_out, "Cache-Control", "no-store");
apr_table_addn(r->err_headers_out, "Cache-Control", "no-store");
/* if set, internal redirect to the logout page */
if (conf->logout) {
apr_table_addn(r->headers_out, "Location", conf->logout);
return HTTP_TEMPORARY_REDIRECT;
}
return HTTP_OK;
}
|
cb56d360c4d2ddf390a7fefc8f304ae4c81a4303
|
cfeac52f970e8901871bd02d9acb7de66b9fb6b4
|
/generated/src/aws-cpp-sdk-lexv2-models/include/aws/lexv2-models/model/TestResultMatchStatus.h
|
e317342fb60a82e9f433be2fc7f857c98bd38f97
|
[
"Apache-2.0",
"MIT",
"JSON"
] |
permissive
|
aws/aws-sdk-cpp
|
aff116ddf9ca2b41e45c47dba1c2b7754935c585
|
9a7606a6c98e13c759032c2e920c7c64a6a35264
|
refs/heads/main
| 2023-08-25T11:16:55.982089
| 2023-08-24T18:14:53
| 2023-08-24T18:14:53
| 35,440,404
| 1,681
| 1,133
|
Apache-2.0
| 2023-09-12T15:59:33
| 2015-05-11T17:57:32
| null |
UTF-8
|
C++
| false
| false
| 744
|
h
|
TestResultMatchStatus.h
|
/**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
#pragma once
#include <aws/lexv2-models/LexModelsV2_EXPORTS.h>
#include <aws/core/utils/memory/stl/AWSString.h>
namespace Aws
{
namespace LexModelsV2
{
namespace Model
{
enum class TestResultMatchStatus
{
NOT_SET,
Matched,
Mismatched,
ExecutionError
};
namespace TestResultMatchStatusMapper
{
AWS_LEXMODELSV2_API TestResultMatchStatus GetTestResultMatchStatusForName(const Aws::String& name);
AWS_LEXMODELSV2_API Aws::String GetNameForTestResultMatchStatus(TestResultMatchStatus value);
} // namespace TestResultMatchStatusMapper
} // namespace Model
} // namespace LexModelsV2
} // namespace Aws
|
7cf5241d45f8dfe50108ff1bde1f505a44a33012
|
c5e143d2e0a98dfe6746494f9c05fd25086b3b4a
|
/itlPlace/src/Buffering/NetBuffering/VGVariantsListElement.h
|
be5de523b4fe89e2e3f8273e251d7058c139fb3c
|
[] |
no_license
|
babooppa6/vlsi-experimental
|
ff3d5a7f34d6034b1ca3c58a7ec6ea79ceb1bd2d
|
b1d1fbb88ef34ca75c2120481d180b503927dc0b
|
refs/heads/master
| 2023-07-23T09:48:03.106961
| 2014-02-13T05:05:38
| 2014-02-13T05:05:38
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,192
|
h
|
VGVariantsListElement.h
|
#ifndef __VGVariantsListElement_H__
#define __VGVariantsListElement_H__
#include "stdTypes.h"
class BufferPositions;
class VGVariantsListElement
{
public:
VGVariantsListElement();
bool operator > (VGVariantsListElement& element);
bool operator < (VGVariantsListElement& element);
bool operator == (VGVariantsListElement& element);
VGVariantsListElement& operator = (VGVariantsListElement& element);
void SortBufferPosition();
double GetRAT();
double GetC();
BufferPositions GetStartBufferPosition();
BufferPositions GetEndBufferPosition();
BufferPositions GetNextBufferPosition();
BufferPositions GetbufferPosition(int i);
int GetPositionCount();
TemplateTypes<BufferPositions>::list* GetBufferPosition();
int GetIndex();
void SetBufferPosition(BufferPositions position);
void SetBufferPosition(TemplateTypes<BufferPositions>::list position);
void SetRAT(double rat);
void SetC(double capacity);
void SetIndex(int i);
protected:
double RAT;
double c;
TemplateTypes<BufferPositions>::list bufferPositions;
int positionCount;
int index;
};
#endif
|
4f987082a3f491d533cf0e7675e7b90193f0eb2f
|
974f810f4634788b13bcb5c2ac717fff375ab924
|
/modules/RenderManager/src/SizeComponent.cpp
|
c70a78b8426d7c536ab2f453be9b2285dd77b96b
|
[] |
no_license
|
mrtrizer/FlappyEngine
|
c5a38974e6ef5d9106bc9dfe8ccfefd98ed58f3e
|
57e7598f9b84c95b17cd332f4f06ac40f8f10467
|
refs/heads/master
| 2020-04-04T06:11:41.067587
| 2019-01-09T21:35:29
| 2019-01-09T21:35:29
| 53,366,417
| 4
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 97
|
cpp
|
SizeComponent.cpp
|
#include "SizeComponent.h"
namespace flappy {
SizeComponent::SizeComponent()
{
}
} // flappy
|
9f86a2215b7e30ee9d3303c52896c4d3705ab4d7
|
2eb738eff0051d3ffa1a932376697565f94cc4d8
|
/include/tiva/tiva.hpp
|
b9f7a3f57a9912208ff3017f044b07d3b37688d9
|
[
"MIT"
] |
permissive
|
akowalew/tivapp
|
a90b8cc8f7263c3118a3e6124e3f45b369ddebb5
|
ba69d4aa0de2aac69881b7ee7b05cd4211304b99
|
refs/heads/master
| 2021-05-09T20:30:27.017949
| 2018-02-01T14:22:37
| 2018-02-01T14:22:37
| 118,696,459
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 90
|
hpp
|
tiva.hpp
|
#pragma once
#include "tiva/gpio.hpp"
#include "tiva/sysctl.hpp"
#include "tiva/uart.hpp"
|
784699be2010fd58efe68dff9772ae607647d365
|
1d9f95efd87912b8e71c32c93402ee84bc503f88
|
/util.h
|
ae2b75e50c0ccfc482797ff5ec1bd35bfb04b0cf
|
[] |
no_license
|
rsatchel/Dijkstras-Shortest-Path
|
b4e02aec7e1a0a2b9331865a6c2475c6e758dd92
|
ff0117a571d33df098a2af91d6af904fa9b51365
|
refs/heads/master
| 2021-01-20T13:27:25.559022
| 2017-05-07T00:10:43
| 2017-05-07T00:10:43
| 90,497,593
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 438
|
h
|
util.h
|
// util.h
// utility files used for heap operations
#ifndef UTIL_H
#define UTIL_H
#include <iostream>
#include "heap.h"
//using namespace std;
void swap(struct VertexNode *E1, struct VertexNode *E2); // swaps 2 specified elements
int parent(int i); // returns parent of specified element
int left(int i); // returns left child of specified element
int right(int i); // returns right child of specified element
#endif
|
ee107068abc8b965e0e148ee01fecc1ac83ee8ce
|
200bcd98cb4b7dbd86589427736323f90ea003f4
|
/blog_coderust/graph_bfs/equal_greedy/equal_greedy.cpp
|
9495b2358e1d960aab601080c9539b92351cf020
|
[] |
no_license
|
amalphonse/Tech_Interview_Prep
|
c022a9d3af647006848f0d9a59a84ee9d907e9a2
|
a2ffb81337ea88061ebe05bf3aaa76bf1108ed94
|
refs/heads/master
| 2021-01-01T18:36:22.928837
| 2017-12-05T20:08:18
| 2017-12-05T20:08:18
| 98,376,894
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,494
|
cpp
|
equal_greedy.cpp
|
/*
Christy is interning at HackerRank. One day she has to distribute some chocolates to her colleagues. She is biased towards her friends and may have distributed the chocolates unequally. One of the program managers gets to know this and orders Christy to make sure everyone gets equal number of chocolates.
But to make things difficult for the intern, she is ordered to equalize the number of chocolates for every colleague in the following manner,
For every operation, she can choose one of her colleagues and can do one of the three things.
She can give one chocolate to every colleague other than chosen one.
She can give two chocolates to every colleague other than chosen one.
She can give five chocolates to every colleague other than chosen one.
Calculate minimum number of such operations needed to ensure that every colleague has the same number of chocolates.
*/
#include<iostream>
#include<vector>
using namespace std;
int ops(int rem) {
int op = 0;
op += rem / 5;
rem %= 5;
op += rem / 2;
rem %= 2;
op += rem;
return op;
}
int main() {
int min = INT_MAX;
int n = 4;
vector<int> v(n);
v.push_back(2);
v.push_back(2);
v.push_back(3);
v.push_back(7);
for (int i = 0; i < n; i++) {
if (v[i] < min) {
min = v[i];
}
}
int answer = INT_MAX;
for (int i = 0; i < 4; i++) {
int temp_answer = 0;
for (int j = 0; j < n; j++) {
temp_answer += ops(v[j] - min + i);
}
if (temp_answer < answer)
answer = temp_answer;
}
cout << answer << endl;
}
|
4773bedff127858ba4ffb97d5cbcae578f544976
|
cc4f275a62299c0fcecc65eb3ddf476d70c7f896
|
/editor/src/editor/widgets/gameView.cpp
|
2e010d1af5dc146ea1e8dcfc49f521728ff85802
|
[
"MIT"
] |
permissive
|
gamezoo/Cjing3D-Test
|
31d794613fb899f40a4fb6d80134d9cbc060b537
|
711667cc7a62fc5d07e7cedd6dfbc57c64bfbfa2
|
refs/heads/master
| 2023-07-01T16:22:29.414792
| 2021-08-10T10:55:53
| 2021-08-10T10:55:53
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,550
|
cpp
|
gameView.cpp
|
#include "gameView.h"
#include "gpu\gpu.h"
#include "imguiRhi\imguiEx.h"
#include "renderer\renderer.h"
#include "renderer\renderScene.h"
#include "renderer\renderPath\renderGraphPath3D.h"
#include "renderer\renderImage.h"
#include "renderer\textureHelper.h"
namespace Cjing3D
{
class EditorWidgetGameViewImpl
{
public:
UniquePtr<RenderPath> mRenderPath = nullptr;
Texture mGameTextrue;
ImVec2 mPrevViewSize;
void ResizeBuffers(const ImVec2& size)
{
mPrevViewSize = size;
mGameTextrue.Clear();
// texture
GPU::TextureDesc texDesc;
texDesc.mWidth = (U32)size.x;
texDesc.mHeight = (U32)size.y;
texDesc.mFormat = GPU::GetBackBufferFormat();
texDesc.mBindFlags = GPU::BIND_RENDER_TARGET | GPU::BIND_SHADER_RESOURCE;
GPU::ResHandle res = GPU::CreateTexture(&texDesc, nullptr, "rtGameView");
mGameTextrue.SetTexture(res, texDesc);
}
void Initialize()
{
mRenderPath = CJING_MAKE_UNIQUE<RenderGraphPath3D>();
mRenderPath->Start();
}
void Uninitialize()
{
mRenderPath->Stop();
mRenderPath.Reset();
}
void Update(F32 deltaTime)
{
if (!mRenderPath) return;
RenderScene* scene = Renderer::GetRenderScene();
if (!scene) {
return;
}
ImVec2 viewPos = ImGui::GetCursorScreenPos();
ImVec2 size = ImGui::GetContentRegionAvail();
if (size.x <= 0 || size.y <= 0) {
return;
}
if ((U32)mPrevViewSize.x != (U32)size.x || (U32)mPrevViewSize.y != (U32)size.y) {
ResizeBuffers(size);
}
mRenderPath->Update(deltaTime);
if (mGameTextrue.GetHandle()) {
ImGui::Image((ImTextureID)mGameTextrue.GetHandlePtr(), size);
}
else {
ImGuiEx::Rect(size.x, size.y, 0xffFF00FF);
}
}
void Draw()
{
RenderScene* scene = Renderer::GetRenderScene();
if (!scene) {
return;
}
mRenderPath->Render();
mRenderPath->Compose(mGameTextrue.GetHandle(), mGameTextrue.GetDesc());
}
};
EditorWidgetGameView::EditorWidgetGameView(GameEditor& editor) :
EditorWidget(editor)
{
mTitleName = "GameView";
mIsWindow = true;
mWidgetFlags = ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_NoNavInputs;
mImpl = CJING_NEW(EditorWidgetGameViewImpl);
}
EditorWidgetGameView::~EditorWidgetGameView()
{
CJING_SAFE_DELETE(mImpl);
}
void EditorWidgetGameView::Initialize()
{
mImpl->Initialize();
}
void EditorWidgetGameView::Uninitialize()
{
mImpl->Uninitialize();
}
void EditorWidgetGameView::Update(F32 deltaTime)
{
mImpl->Update(deltaTime);
}
void EditorWidgetGameView::Draw()
{
mImpl->Draw();
}
}
|
48baac9004679a4e24f7635dc9e2b64c98f89f94
|
c30c3466c34c41b49e8c8b2791e0d44ae6277cb2
|
/Cowcycles/src/Cowcycles.cpp
|
7624c0b1494bff5329dbf1faff486c5b84de0d03
|
[] |
no_license
|
theAnton-forks/Competitive-Programming-Portfolio
|
784eb9ff5441f1a81f5501d690f9094698bc34c7
|
fb3f099d7ecc37b9117d64faa4c1bdf89e1f18d2
|
refs/heads/master
| 2022-12-14T03:18:04.941318
| 2020-09-03T05:22:46
| 2020-09-03T05:22:46
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,791
|
cpp
|
Cowcycles.cpp
|
/*
ID: vlade.m1
PROG: cowcycle
LANG: C++
*/
#include <bits/stdc++.h>
typedef long long ll;
using namespace std;
const int maxn = 1e3;
int val[maxn];
int f, r;
int f1, f2, r1, r2;
vector<int> fl, rl;
vector<int> fb, rb;
double v[maxn];
double best_standard = 1e9;
void check(){
for(int i = 0; i < fl.size(); i++){
for(int j = 0; j < rl.size(); j++){
v[i * rl.size() + j] = ((double) fl[i]) / ((double) rl[j]);
}
}
sort(v, v + fl.size() * rl.size());
if(v[fl.size() * rl.size() - 1] < 3.0 * v[0]){
return;
}
double mean = 0;
for(int i = 1; i < fl.size() * rl.size(); i++){
v[i - 1] = abs(v[i] - v[i - 1]);
mean += v[i - 1];
}
mean /= (double) (fl.size() * rl.size() - 1.0);
double check_standard = 0.0;
for(int i = 0; i < fl.size() * rl.size() - 1; i++){
check_standard += (mean - v[i]) * (mean - v[i]);
}
if(check_standard < best_standard){
best_standard = check_standard;
fb = fl, rb = rl;
}
}
void dfs(int pos, int last, int eend){
if(pos == 0){
last = f1;
eend = f2;
} else if(pos == f){
last = r1;
eend = r2;
} else if(pos == f + r){
check();
return;
}
for(; last <= eend; last++){
if(pos < f){
fl[pos] = last;
dfs(pos + 1, last + 1, eend);
} else {
rl[pos - f] = last;
dfs(pos + 1, last + 1, eend);
}
}
}
int main(){
ios::sync_with_stdio(false); cin.tie(0); cout.tie(0);
// freopen("cowcycle.in", "r", stdin);
// freopen("cowcycle.out", "w", stdout);
cin >> f >> r;
cin >> f1 >> f2 >> r1 >> r2;
fl.resize(f);
rl.resize(r);
dfs(0, f1, f2);
for(int i = 0; i < fb.size(); i++){
cout << fb[i];
if(i != fb.size() - 1){
cout << ' ';
} else {
cout << endl;
}
}
for(int i = 0; i < rb.size(); i++){
cout << rb[i];
if(i != rb.size() - 1){
cout << ' ';
} else {
cout << endl;
}
}
}
|
5aedcfcd5b89e27f7711f94d377fbc41173eb32f
|
c26ad913f9408b0cf713fcac1e9071727db87a37
|
/codeforces/1244/B.cpp
|
d1dc2d41d51044d9b37b365a0a20ecabaa37c7ac
|
[] |
no_license
|
anuragjha8/Codeforces
|
40fe895b09b57f07a96528c71a0d66d33804f488
|
7805cadf24d3830d074864a6540bb959a065a63e
|
refs/heads/master
| 2023-02-19T06:07:27.821578
| 2020-08-22T12:06:00
| 2021-01-22T06:09:49
| 331,848,407
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 383
|
cpp
|
B.cpp
|
#include <bits/stdc++.h>
using namespace std;
int main() {
int t;
cin >> t;
while(t--){
int n,x=0,y=0;
cin >> n;
string a;
cin >> a;
vector<int>v;
for(int i=0;i<n;i++){
if(a[i]=='1')
v.push_back(max(i+1,n-i));
//cout<<max(i+1,n-i);
}
sort(v.begin(),v.end());
y=v.size();
x=v[y-1];
if(y==0)
cout<<n<<endl;
else
cout<<2*x<<endl;
}
return 0;
}
|
5cb372faf9ad563593d75160983c9e0bc1eedfaf
|
1acf60dd59c1078cce3cb694eeeabd771443c446
|
/CSE109-SystemsSoftware/Prog5/Compiler/parser.h
|
af40ea20e699e1cd5fe398f305517060a1d64800
|
[] |
no_license
|
yay218/LehighCourseCode
|
22918721105839ea45cb0bc5d512386ae66daace
|
482f0a207aaf326383307911311f4ff6fa746b4a
|
refs/heads/master
| 2022-11-02T04:41:47.390031
| 2020-06-06T22:07:26
| 2020-06-06T22:07:26
| 270,111,743
| 1
| 0
| null | 2020-06-06T22:06:12
| 2020-06-06T21:40:30
|
Java
|
UTF-8
|
C++
| false
| false
| 990
|
h
|
parser.h
|
/* CSE 109
Yang Yi
yay218
Program Description: This program develops a lexical analyzer,
which will act as a tokenizer for the compiler we are developing in
class.
Program #5
*/
#ifndef PARSER_H
#define PARSER_H
#include "token.h"
#include "lexer.h"
#include <iostream>
#include <string>
#include <cstring>
#include <stdlib.h>
#include <sstream>
using namespace std;
class Parser {
public:
class TreeNode {
};
private:
Lexer lexer;
Token token;
ostream& out;
void error(string message);
void check(int tokenType, string message);
public:
TreeNode *program();
TreeNode* compoundStatement();
TreeNode* statement();
TreeNode* setStatement();
TreeNode* printStatement();
TreeNode* whileStatement();
TreeNode* ifStatement();
TreeNode* logicalExpression();
TreeNode* relationalExpression();
TreeNode* expression();
TreeNode* term();
TreeNode* factor();
Parser(Lexer& lexer, ostream& out);
~Parser();
};
#endif
|
4f73097963c4c8e895ad69cb60cbbc6293a6bddd
|
1a64968217a2f85f01191c3982f2680f06840705
|
/RavensbourneClient/polyline.cpp
|
093f07ac0b09844c99aa114e41e39658028770f6
|
[] |
no_license
|
surgerydar/RavensbourneTable
|
790172a5f9098c19b048f07e5c101f9c01a54192
|
ac9cbf8a3759bc34c389d6cac9b17438c0fd8e8e
|
refs/heads/master
| 2021-01-13T13:48:23.731282
| 2017-06-29T16:32:41
| 2017-06-29T16:32:41
| 76,140,344
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 9,072
|
cpp
|
polyline.cpp
|
#include <QVariant>
#include <QVariantList>
#include <QVariantMap>
#include <QPointF>
#include <QLine>
#include <QUuid>
#include <QDebug>
#include <cmath>
#include "polyline.h"
const int curveResolution = 30;
const float distanceThreshold = 20.;
PolyLine::PolyLine() :
m_hasChanged(false),
m_lineWidth(4) {
m_id = QUuid::createUuid().toString();
}
void PolyLine::start( QVector2D& p ) {
m_points.clear();
m_curveVertices.clear();
m_points.push_back(p);
m_hasChanged = true;
}
void PolyLine::lineto( QVector2D& p ) {
m_curveVertices.clear();
m_points.push_back(p);
m_hasChanged = true;
}
void PolyLine::curveto( QVector2D& p ) {
m_curveVertices.push_back(p);
if (m_curveVertices.size() == 4) {
float x0 = m_curveVertices[0].x();
float y0 = m_curveVertices[0].y();
float x1 = m_curveVertices[1].x();
float y1 = m_curveVertices[1].y();
float x2 = m_curveVertices[2].x();
float y2 = m_curveVertices[2].y();
float x3 = m_curveVertices[3].x();
float y3 = m_curveVertices[3].y();
float t,t2,t3;
float x,y;
for (int i = 0; i < curveResolution; i++){
t = (float)i / (float)(curveResolution-1);
t2 = t * t;
t3 = t2 * t;
x = 0.5f * ( ( 2.0f * x1 ) +
( -x0 + x2 ) * t +
( 2.0f * x0 - 5.0f * x1 + 4 * x2 - x3 ) * t2 +
( -x0 + 3.0f * x1 - 3.0f * x2 + x3 ) * t3 );
y = 0.5f * ( ( 2.0f * y1 ) +
( -y0 + y2 ) * t +
( 2.0f * y0 - 5.0f * y1 + 4 * y2 - y3 ) * t2 +
( -y0 + 3.0f * y1 - 3.0f * y2 + y3 ) * t3 );
m_points.push_back(QVector2D(x,y));
}
m_curveVertices.pop_front();
}
m_hasChanged = true;
}
void PolyLine::move(const QVector2D& by ) {
for ( auto& point : m_points ) {
point += by;
}
}
QPolygonF& PolyLine::polygon() {
if ( hasChanged() ) {
//
//
//
m_polygon.clear();
for ( auto& vect : m_points ) {
QPointF point( vect.x(), vect.y() );
m_polygon.append(point);
}
}
return m_polygon;
}
//
//
//
bool PolyLine::hasChanged() {
if( m_hasChanged ){
m_hasChanged=false;
return true;
} else {
return false;
}
}
//
//
//
QRectF PolyLine::getBounds() {
if ( m_points.size() == 0 ) return QRect();
qreal min_x = std::numeric_limits<qreal>::max();
qreal max_x = std::numeric_limits<qreal>::min();
qreal min_y = std::numeric_limits<qreal>::max();
qreal max_y = std::numeric_limits<qreal>::min();
for ( auto& point : m_points ) {
if ( point.x() < min_x ) min_x = point.x();
if ( point.x() > max_x ) max_x = point.x();
if ( point.y() < min_y ) min_y = point.y();
if ( point.x() > max_y ) max_y = point.y();
}
return QRectF( min_x, min_y, max_x - min_x, max_y - min_y );
}
//
//
//
static QVector2D nearestPointOnLine( const QVector2D& p1, const QVector2D& p2, const QVector2D& p3 ) {
if ( p1 == p2 ) {
return p1;
}
float u = (p3.x() - p1.x()) * (p2.x() - p1.x());
u += (p3.y() - p1.y()) * (p2.y() - p1.y());
// perfect place for fast inverse sqrt...
QVector2D d = p2 - p1;
float len = d.length();
u /= (len * len);
// clamp u
if(u > 1) {
u = 1;
} else if(u < 0) {
u = 0;
}
return p1 + ( d * u );
}
QVector2D PolyLine::nearestPoint( const QVector2D& target ) const {
float minDistance = std::numeric_limits<float>::max();
QVector2D nearest;
int count = m_points.size() - 1;
for ( int i = 0; i < count; i++ ) {
QVector2D point = nearestPointOnLine( m_points[ i ], m_points[ i+ 1 ], target );
float distance = ( point - target ).length();
if ( distance < minDistance ) {
minDistance = distance;
nearest = point;
}
}
return nearest;
}
QVariant PolyLine::save() {
QVariantList points;
for ( auto& vect : m_points ) {
QVariantMap point;
point["x"] = QVariant::fromValue(vect.x());
point["y"] = QVariant::fromValue(vect.y());
points.append(QVariant::fromValue(point));
}
QVariantMap object;
object["id"] = QVariant(m_id);
object["colour"] = QVariant(m_colour);
object["linewidth"] = QVariant(m_lineWidth);
object["points"] = QVariant::fromValue(points);
return QVariant::fromValue(object);
}
void PolyLine::load( const QVariant& line ) {
QVariantMap lineMap = line.toMap();
m_id = lineMap.contains("id") ? lineMap["id"].value<QString>() : QUuid::createUuid().toString();
m_colour = lineMap.contains("colour") ? lineMap["colour"].value<QColor>() : m_colour;
m_lineWidth = lineMap.contains("linewidth") ? lineMap["linewidth"].value<int>() : m_lineWidth;
QVariantList points = lineMap["points"].toList();
int count = points.size();
qDebug() << "PolyLine::load : " << count << " points";
m_points.resize(count);
for ( int i = 0; i < count; i++ ) {
QVariantMap pointMap = points[ i ].toMap();
m_points[ i ].setX(pointMap["x"].value<float>());
m_points[ i ].setY(pointMap["y"].value<float>());
}
m_hasChanged = true;
}
// dot product (3D) which allows vector operations in arguments
#define dot(u,v) ((u).x() * (v).x() + (u).y() * (v).y() )
#define norm2(v) dot(v,v) // norm2 = squared length of vector
#define norm(v) sqrt(norm2(v)) // norm = length of vector
#define d2(u,v) norm2(u-v) // distance squared = norm2 of difference
#define d(u,v) norm(u-v) // distance = norm of difference
//--------------------------------------------------
static void simplifyDP(float tol, QVector2D* v, int j, int k, int* mk ){
if (k <= j+1) // there is nothing to simplify
return;
// check for adequate approximation by segment S from v[j] to v[k]
int maxi = j; // index of vertex farthest from S
float maxd2 = 0; // distance squared of farthest vertex
float tol2 = tol * tol; // tolerance squared
QVector2D p0 = v[j];
QVector2D p1 = v[k]; // segment from v[j] to v[k]
QVector2D u = p1 - p0; // segment direction vector
double cu = dot(u,u); // segment length squared
// test each vertex v[i] for max distance from S
// compute using the Feb 2001 Algorithm's dist_ofPoint_to_Segment()
// Note: this works in any dimension (2D, 3D, ...)
QVector2D w;
QVector2D Pb; // base of perpendicular from v[i] to S
float b, cw, dv2; // dv2 = distance v[i] to S squared
for (int i=j+1; i<k; i++){
// compute distance squared
w = v[i] - p0;
cw = dot(w,u);
if ( cw <= 0 ) dv2 = d2(v[i], p0);
else if ( cu <= cw ) dv2 = d2(v[i], p1);
else {
b = (float)(cw / cu);
Pb = p0 + u*b;
dv2 = d2(v[i], Pb);
}
// test with current max distance squared
if (dv2 <= maxd2) continue;
// v[i] is a new max vertex
maxi = i;
maxd2 = dv2;
}
if (maxd2 > tol2) // error is worse than the tolerance
{
// split the polyline at the farthest vertex from S
mk[maxi] = 1; // mark v[maxi] for the simplified polyline
// recursively simplify the two subpolylines at v[maxi]
simplifyDP( tol, v, j, maxi, mk ); // polyline v[j] to v[maxi]
simplifyDP( tol, v, maxi, k, mk ); // polyline v[maxi] to v[k]
}
// else the approximation is OK, so ignore intermediate vertices
return;
}
//--------------------------------------------------
void PolyLine::simplify(float tol){
if(m_points.size() < 2) return;
int n = m_points.size();
qDebug() << "PolyLine::simplify : before : " << n;
QVector<QVector2D> sV;
sV.resize(n);
int i, k, m, pv; // misc counters
float tol2 = tol * tol; // tolerance squared
QVector<QVector2D> vt;
QVector<int> mk;
vt.resize(n);
mk.fill(0,n);
// STAGE 1. Vertex Reduction within tolerance of prior vertex cluster
vt[0] = m_points[0]; // start at the beginning
for (i=k=1, pv=0; i<n; i++) {
if (d2(m_points[i], m_points[pv]) < tol2) continue;
vt[k++] = m_points[i];
pv = i;
}
if (pv < n-1) vt[k++] = m_points[n-1]; // finish at the end
// STAGE 2. Douglas-Peucker polyline simplification
mk[0] = mk[k-1] = 1; // mark the first and last vertices
simplifyDP( tol, &vt[0], 0, k-1, &mk[0] );
// copy marked vertices to the output simplified polyline
for (i=m=0; i<k; i++) {
if (mk[i]) sV[m++] = vt[i];
}
m_points = sV;
if( m < (int)m_points.size() ) {
//get rid of the unused points
m_points.resize(m);
}
qDebug() << "PolyLine::simplify : after : " << m;
}
|
fb5fe8f97cd173d61635382687c743b5e724f626
|
6c742cb7ff21b7cfb88cf9106ca5c24b417dfe9f
|
/identClass.h
|
8e65f1feda5e82793f206500d95453a38b57323b
|
[] |
no_license
|
nomoreclowns/cs421hw3
|
c7bc0ce24a9f8fffc1e34ce39a89eb1b4239cd4e
|
5e8c47390bc2ea3ebb3c6aae1366cb57bb6c732f
|
refs/heads/master
| 2020-05-19T13:05:24.427205
| 2014-03-11T07:39:57
| 2014-03-11T07:39:57
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 138
|
h
|
identClass.h
|
#include <string>
using namespace std;
class identDFA
{
public:
bool ident_token(string);
int q0(char);
int q1(char);
};
|
8589cec9e0aeac5ea4b4938fc3afea387765f2da
|
f023b5cb59c4b41e28617294b458822968c3aa4c
|
/lab06/huffman_tree_node.hpp
|
8482f0a86704a711bf4cf502ab402d9938e8e5d1
|
[] |
no_license
|
wcdbmv/IS
|
4efd24bc850740ba6e8a86d8d1bfcb3a36ca7e3b
|
d81125830b95b19446dd4bff6f99f16155d452ec
|
refs/heads/master
| 2023-01-24T23:27:38.226840
| 2020-12-09T20:58:24
| 2020-12-09T20:58:24
| 297,056,706
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 262
|
hpp
|
huffman_tree_node.hpp
|
#pragma once
#include <cstdint>
#include "binary_tree_node.hpp"
struct HuffmanData {
using character_type = uint8_t;
using frequency_type = uint32_t;
character_type character;
frequency_type frequency;
};
using HuffmanNode = BinaryTreeNode<HuffmanData>;
|
dc36d250ae9c785db3ecdd56579f0bdea3feabbe
|
2f6a9ff787b9eb2ababc9bb39e15f1349fefa3d2
|
/inet/tests/unit/lib/TCPQueueTesterFunctions.h
|
b9f41b4e558bcc94df666175e05dcf7539453aeb
|
[
"BSD-3-Clause",
"MPL-2.0",
"LicenseRef-scancode-free-unknown"
] |
permissive
|
ntanetani/quisp
|
97f9c2d0a8d3affbc709452e98c02c568f5fe8fd
|
47501a9e9adbd6adfb05a1c98624870b004799ea
|
refs/heads/master
| 2023-03-10T08:05:30.044698
| 2022-06-14T17:29:28
| 2022-06-14T17:29:28
| 247,196,429
| 0
| 1
|
BSD-3-Clause
| 2023-02-27T03:27:22
| 2020-03-14T02:16:19
|
C++
|
UTF-8
|
C++
| false
| false
| 1,029
|
h
|
TCPQueueTesterFunctions.h
|
#ifndef __TEST__TCPQUEUETESTER_FUNCTIONS
#include "inet/common/packet/Packet.h"
#include "inet/transportlayer/tcp/TcpReceiveQueue.h"
#include "inet/transportlayer/tcp/TcpSendQueue.h"
using namespace inet;
using namespace tcp;
// TcpSendQueue:
void enqueue(TcpSendQueue *sq, const char *msgname, ulong numBytes);
void tryenqueue(TcpSendQueue *sq, const char *msgname, ulong numBytes);
Packet *createSegmentWithBytes(TcpSendQueue *sq, uint32 fromSeq, uint32 toSeq);
void discardUpTo(TcpSendQueue *sq, uint32 seqNum);
//////////////////////////////////////////////////////////////
// TcpReceiveQueue:
void insertSegment(TcpReceiveQueue *rq, Packet *tcpseg);
void tryinsertSegment(TcpReceiveQueue *rq, Packet *tcpseg);
void extractBytesUpTo(TcpReceiveQueue *rq, uint32 seq);
void insertSegment(TcpReceiveQueue *q, uint32 beg, uint32 end);
void tryinsertSegment(TcpReceiveQueue *q, uint32 beg, uint32 end);
/////////////////////////////////////////////////////////////////////////
#endif // __TEST__TCPQUEUETESTER_FUNCTIONS
|
170d9ac3d59d877f72b70724af1345895e52fc29
|
33cc75a925b12133bc78fe0f307140878bb093b6
|
/oia/train-2019/A2/8/main.cpp
|
da87de0ee85d0c0fa8f893942d771ce340d54905
|
[] |
no_license
|
redeff/cmp
|
05603369f404cff25d168105b1f1c7a956fd07b8
|
8974bacf61b6c73d1cb5d3b5aa33c12af0d687d0
|
refs/heads/master
| 2021-05-08T01:10:47.542693
| 2019-10-13T22:19:32
| 2019-10-13T22:19:32
| 107,782,810
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 484
|
cpp
|
main.cpp
|
#include <bits/stdc++.h>
using namespace std;
int main() {
cin.tie(0);
ios::sync_with_stdio(0);
int n;
cin >> n;
vector<string> ns(n);
for(int i = 0; i < n; ++i) {
cin >> ns[i];
}
for(int i = n - 1; i > 0; --i) {
int k = 0;
while(k < ns[i].size() && k < ns[i-1].size() && ns[i][k] == ns[i-1][k]) k++;
if(k == ns[i].size() || k == ns[i-1].size() || ns[i][k] < ns[i-1][k])
while(ns[i-1].size() > k) ns[i-1].pop_back();
}
for(string s : ns) cout << s << endl;
}
|
ef509afa8239599791f6e9d5eeb00b374ff77238
|
3b364f228714e23229096926b290ab83ae9c1f49
|
/Linked List Practice/sll.h
|
85d07291b3648ca6b0c2192510f599ccf295170b
|
[] |
no_license
|
rbmauric/Linked-List-Practice
|
5e4349be7aadddd138836d71fd8d7ec947a4e327
|
cfb094696cf521c59604b26d6dfa0322d5bd0239
|
refs/heads/master
| 2020-09-06T11:24:20.650311
| 2019-12-02T02:59:57
| 2019-12-02T02:59:57
| 220,410,869
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 585
|
h
|
sll.h
|
#ifndef SLL_H
#define SLL_H
template<typename T>
class Node { //Singly linked list node contains a next pointer and an element
public:
Node() {
elem = 0;
next = nullptr;
}
Node(T elem_) {
elem = elem_;
next = nullptr;
}
T elem;
Node<T>* next;
};
template <typename T>
class SLL { //Singly linked list contains a head pointer.
public:
SLL();
void addFront(T elem);
void insertAt(T elem, int n);
void removeFront();
void removeAt(int n);
void clear();
Node<T>* front();
Node<T>* at(int n);
int size();
void print();
private:
Node<T>* head;
};
#endif SLL_H
|
d23704a422222bd0e6e59bfd06e7be4b45aa1c81
|
a134d441ce9207db8a75c6e97c87d19b7053aa8d
|
/robot_qubits.ino
|
a430ade01e3b986f6a0994b2d0b7989b42b305df
|
[] |
no_license
|
thelegend831/Qubits-transporter-robot
|
28623fd92e6b35ac18339ce99a3ea13e0ac4a788
|
82325b9cf456dfec1aee2e7a1fc8057db1e54031
|
refs/heads/master
| 2021-06-20T23:21:48.030634
| 2017-08-05T16:43:45
| 2017-08-05T16:43:45
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,884
|
ino
|
robot_qubits.ino
|
#include "Shared.h"
#include "Movement.h"
#include "Arm.h"
#include "LineFollower.h"
String cmd;
int cmdNum;
void readBluethooth();
void setup() {
//Setup pins
setupMotor();
setupArm();
setupLineFollower();
Serial.begin(9600);
}
void loop() {
if(digitalRead(P_LF_SWITCH) == HIGH){
autoDrive();
}else{
readBluethooth();
}
}
void readBluethooth(){
if (Serial.available() > 0) {
cmd = Serial.readString();
Serial.println(cmd);
switch(cmd[0]){
case 'M': //Movement
readMovement();
break;
case 'A': //Arm
readArm();
break;
}
}
}
void readMovement(){
switch(cmd[1]){
case 'F':
moveRobot(FORWARD);
Serial.println("Robot Forward");
break;
case 'B':
moveRobot(BACKWARD);
Serial.println("Robot Back");
break;
case 'L':
turnRobot(LEFT);
Serial.println("Robot Left");
break;
case 'R':
turnRobot(RIGHT);
Serial.println("Robot Back");
break;
}
}
void readArm(){
switch(cmd[1]){
case 'R':
moveArmBase(RIGHT);
Serial.println("Arm Right");
break;
case 'L':
moveArmBase(LEFT);
Serial.println("Arm Left");
break;
case 'G':
moveArmGripper(GRAB);
Serial.println("Arm Grab");
break;
case 'S':
moveArmGripper(RELEASE);
Serial.println("Arm Relese");
break;
case 'E':
cmdNum = charToInt(cmd[2]);
moveArmJoint(cmdNum,EXTEND);
Serial.print("Arm Extend");
Serial.println(cmdNum);
break;
case 'C':
cmdNum = charToInt(cmd[2]);
moveArmJoint(cmdNum,COLLAPSE);
Serial.print("Arm Collapse");
Serial.println(cmdNum);
break;
}
}
int charToInt(char c){
if(c=='1')return 1;
else if(c=='2')return 2;
else return -1;
}
|
efd12b6abd42c0516f5681eb90269b4544d530bf
|
5f975169aeb67c7cd0a08683e6b9eee253f84183
|
/algorithms/medium/1536. Minimum Swaps to Arrange a Binary Grid.h
|
01c8f09ff5a5e33bf65abfc86b27723a3f4e8a3a
|
[
"MIT"
] |
permissive
|
MultivacX/leetcode2020
|
6b743ffb0d731eea436d203ccb221be14f2346d3
|
83bfd675052de169ae9612d88378a704c80a50f1
|
refs/heads/master
| 2023-03-17T23:19:45.996836
| 2023-03-16T07:54:45
| 2023-03-16T07:54:45
| 231,091,990
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,308
|
h
|
1536. Minimum Swaps to Arrange a Binary Grid.h
|
// 1536. Minimum Swaps to Arrange a Binary Grid
// https://leetcode.com/problems/minimum-swaps-to-arrange-a-binary-grid/
// Runtime: 132 ms, faster than 60.69% of C++ online submissions for Minimum Swaps to Arrange a Binary Grid.
// Memory Usage: 26.1 MB, less than 42.20% of C++ online submissions for Minimum Swaps to Arrange a Binary Grid.
class Solution {
public:
int minSwaps(vector<vector<int>>& grid) {
const int N = grid.size();
vector<int> zeros(N, 0);
for (int i = 0; i < N; ++i) {
for (int j = N - 1; j >= 0; --j) {
if (grid[i][j] == 1) break;
++zeros[i];
}
}
// for (int i = 0; i < N; ++i) cout << i << ":" << zeros[i] << ", "; cout << endl;
int ans = 0;
for (int i = 0; i < N; ++i) {
// min zeros at [i]
int z = N - i - 1;
if (zeros[i] >= z) continue;
// find zeros[j] >= z
int j = i + 1;
while (j < N && zeros[j] < z) ++j;
if (j >= N) return -1;
// swap j to i
while (j > i) {
swap(zeros[j - 1], zeros[j]);
--j;
++ans;
}
}
return ans;
}
};
|
9b92607fd5e8367fc190023c3f018e6538904a79
|
686af39e5a17176a7a6d43effa442af69e5001e7
|
/CP_Handbook/dynamic_programming.cpp
|
c8882e5bb257cfca19ea0a82ba3abeafdaef8026
|
[] |
no_license
|
mady16/MycppCodes
|
aba2756d1e96b658bde0c24cb6187138f463c517
|
e3e3b4f2b2f071a567c65f33297442742092235f
|
refs/heads/master
| 2022-02-23T02:55:11.809075
| 2019-09-20T19:16:01
| 2019-09-20T19:16:01
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,100
|
cpp
|
dynamic_programming.cpp
|
#include <algorithm>
#include <cmath>
#include <iostream>
#include <string>
#include <vector>
using namespace std;
typedef long long ll;
#define foreq(i, a, b) for (int i = a; i <= b; i++)
#define forless(i, a, b) for (int i = a; i < b; i++)
#define rforeq(i, a, b) for (int i = a; i >= b; i--)
#define rforless(i, a, b) for (int i = a; i > b; i--)
#define printA(A, n) \
foreq(p, 0, n - 1) { cout << A[p] << " "; } \
cout << endl;
#define print(s) cout << s << endl
#define scan(s) cin >> s
#define scanA(A, n) \
foreq(p, 0, n - 1) { cin >> A[p]; }
#define sq(a) (a) * (a)
// ios::sync_with_stdio(0);
// cin.tie(0);
int countCoins(int coins[], int *storage, int x, int n) {
if (x < 0) return INT16_MAX;
if (x == 0) return 0;
// print(x);
if (storage[x] != -1) return storage[x];
int best = INT16_MAX;
forless(i, 0, n) {
best = min(best, countCoins(coins, storage, x - coins[i], n) + 1);
}
storage[x] = best;
return best;
}
int maxPathinGrid(int grid[][6]) {
int sum[6][6];
forless(i, 0, 6) {
sum[0][i] = 0;
sum[i][0] = 0;
}
forless(i, 1, 6) {
forless(j, 1, 6) {
sum[i][j] = max(sum[i - 1][j], sum[i][j - 1]) + grid[i][j];
}
}
return sum[5][5];
}
int editDistance(string str1, string str2, int m, int n) {
if (m == 0) return n;
if (n == 0) return m;
if (str1[m-1] == str2[n-1]) return editDistance(str1, str2, m - 1, n - 1);
return 1 + min(min(editDistance(str1, str2, m, n - 1),
editDistance(str1, str2, m - 1, n)),
editDistance(str1, str2, m - 1, n - 1));
}
int main() {
int coins[] = {1, 3, 4};
int storage[10020];
forless(i, 0, 10020) storage[i] = -1;
print(countCoins(coins, storage, 10012, 3));
int grid[6][6] = {
{0, 0, 0, 0, 0, 0}, {0, 2, 4, 5, 6, 1}, {0, 1, 3, 3, 6, 8},
{0, 7, 1, 2, 3, 7}, {0, 2, 8, 4, 2, 2}, {0, 1, 7, 8, 6, 1},
};
print(maxPathinGrid(grid));
print(editDistance("love", "movie", 4, 5));
return 0;
}
|
13213ee2ba94d08b2badd7aa1b4e6615ce6030a2
|
13b572ca5562ff9623087222d2e1dd35d5d46b7e
|
/Dataset.cpp
|
40ed1c8bb032fc78c061c4a7568a5808de8e15b9
|
[] |
no_license
|
ashishd/SfM
|
4e3dcbfe5173f84b2211a87e07f82998f7ede14e
|
2a97bd64e264aa43ef38a24081889002ffe00e2b
|
refs/heads/master
| 2022-12-12T12:38:56.881567
| 2020-09-09T19:01:29
| 2020-09-09T19:01:29
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 278
|
cpp
|
Dataset.cpp
|
#include "Dataset.h"
Dataset::Dataset(const string& path):_path(path){
ReadImgs();
}
void Dataset::ReadImgs(){
glob(_path + "/*.ppm", _filenames, false);
size_t count = _filenames.size();
for (size_t i =0; i<count; ++i)
_images.push_back(imread(_filenames[i]));
}
|
1869a8e72db556a30e5550f90fb5cc1d0f47d2b2
|
d253ce633c06f579db1636733428053d2fcbca50
|
/snir1String/snir1String/main.cpp
|
1be475fdfe1feeb8e8063f78b53d1640b15ea8db
|
[] |
no_license
|
ctonnerre/snir1String
|
3c5ae76bd66319b3ed1ef8fc088bab72022ecb89
|
7618be4b1a269bc09294171080f15e9ddcc113e6
|
refs/heads/master
| 2021-03-07T13:58:37.257800
| 2020-03-18T12:06:26
| 2020-03-18T12:06:26
| 246,270,573
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 3,406
|
cpp
|
main.cpp
|
//
// main.cpp
// snir1String
//
// Created by Cécile Tonnerre on 11/03/2020.
// Copyright © 2020 Cécile Tonnerre. All rights reserved.
//
#include <iostream>
// include pour les objets de type string C++
#include <string>
// include pour utiliser les string comme en C
#include <string.h>
using namespace std;
int main(int argc, const char * argv[]) {
/**************************************************************************/
/* utilisation des chaînes de caractères mode c++ : objet de type string */
/**************************************************************************/
cout << "+++++++++++++++++++++++++++++++++++++++++++++++++++++" << endl;
cout << "\tUtilisation en C++ de l'objet de type string " << endl;
string maChaine ("Les sanglots longs des violons de l'automne ");
cout << maChaine << endl;
// utilisation pour le TP
string requete("INSERT INTO mesures (temperature) VALUES (");
char buf[255] = "Temp[0]: +18.06 degC";
string maTemperature ("NULL");
string buffer(buf);
cout << "ma ligne : " << buffer << endl;
if ( buffer.find("Temp[0]") != string::npos )
{
cout << "Victoire on a la temperature " << endl ;
buffer.replace(0, 9, "");
cout << "ma ligne apres replace 1: -" << buffer << "- " << endl;
buffer.replace(6, 9, "");
cout << "ma ligne apres replace 2: -" << buffer << "- " << endl;
}
// il reste à créer la requete de la forme
// INSERT INTO mesures (temperature) VALUES (+18.06);
requete = requete + buffer;
cout << " requete avec le + " << requete << endl;
// calcul de la longueur : utilisation de la méthode length()
cout << "\tde longeur : " << maChaine.length() << endl ;
// cherche la chaîne "violons" dans maChaine : utilisation de la méthode find()
cout << " est-ce qu'il y a violons dedans ? " << maChaine.find("violons") << endl;
if (maChaine.find("violons") == string::npos )
{
cout << " violons n'apparaît pas dans maChaine " <<endl << endl;
}
cout << " est-ce qu'il y a guitares dedans ? " << maChaine.find("guitares") << endl;
if (maChaine.find("guitares") == string::npos )
{
cout << " guitares n'apparaît pas dans maChaine " <<endl << endl;
}
// je concatene avec l'operateur '+'
maChaine += "\nBlessent mon coeur d'une langueur monotone";
cout << "\tMa nouvelle chaine après concaténation " << endl;
cout << maChaine << endl;
cout << "\tde longueur " << maChaine.length() << endl <<endl ;
// effacer des caractères : utilisation de la méthode erase()
// effacement de la première ligne de longueur 23
maChaine.erase(0,44);
cout << "\tMa nouvelle chaîne raccourcie par l'avant " << endl;
cout << maChaine << endl;
cout << "\tde longeur : " << maChaine.length() << endl ;
/**************************************************************************/
/* utilisation des chaînes de caractères mode c++ : objet de type string */
/**************************************************************************/
char maChaineC[] = "Les sanglots longs des violons de l'automne ";
char *trouveChaine = nullptr;
cout << endl << endl;
cout << "cherche chaine c " << strstr(maChaineC, "violons") << endl;
//decoupe (tokenzie) avec
return 0;
}
|
d7ae6f908be71a3099e948e7da2b52cf590345d5
|
f6636e9bc98ba02c242b82f469e0587755595961
|
/point.hpp
|
83233254c3569600e54e951b7f027362103c154f
|
[] |
no_license
|
ivaniesta14/i14extra
|
5a7265ecea88b007f6a12128d3678f13b302faee
|
b78981cea0cc23b9ad22637d3395cde06e52f3e8
|
refs/heads/master
| 2021-01-18T19:34:21.646942
| 2018-07-27T12:03:42
| 2018-07-27T12:03:42
| 100,533,394
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 4,244
|
hpp
|
point.hpp
|
#ifndef I14EXTRA_POINT_HPP
#define I14EXTRA_POINT_HPP
#include <complex>
#include <utility>
#include <tuple>
#include <type_traits>
#include "i14extra/convenience.hpp"
namespace i14extra {
template <typename T>
class point_t{
static_assert(std::is_arithmetic_v<T>,
"i14extra::point<T>: T must be arithmetic");
public:
typedef T value_type;
T x,y,z;
constexpr point_t(const T& vx=*new T(),const T& vy=*new T(),
const T& vz=*new T()):
x(static_cast<T>(vx)),y(static_cast<T>(vy)),z(static_cast<T>(vz)){}
template<typename U>constexpr point_t(point_t<U> cref other):
point_t(other.x,other.y,other.z){}
template<typename U>
constexpr point_t(const std::complex<U>& other):
point_t(static_cast<T>(other.real()),static_cast<T>(other.imag())){}
template<typename U,typename V>
constexpr point_t(const std::pair<U,V>& other):
point_t(static_cast<T>(other.first),static_cast<T>(other.second)){}
template<typename U,typename V,typename W>
constexpr point_t(const std::tuple<U,V,W>& other):point_t(
static_cast<T>(std::get<U>(other)),
static_cast<T>(std::get<V>(other)),
static_cast<T>(std::get<W>(other))){}
explicit inline operator T(){return x;}
template<typename U=T> explicit
inline operator std::complex<U>(){return *new std::complex<U>(x,y);}
template<typename U=T,typename V=T> explicit
inline operator std::pair<U,V>(){return std::make_pair(x,y);}
template<typename U=T,typename V=T,typename W=T> explicit
inline operator std::tuple<U,V,W>(){return std::make_tuple(x,y,z);}
inline const point_t<T>& operator=(const point_t<T>& rhs){
x=rhs.x;
y=rhs.y;
z=rhs.z;
return *this;
}
inline const point_t<T>& operator=(const T& rhs){
x=rhs;
y=0;
z=0;
return *this;
}
inline const point_t<T>& operator=(const std::complex<T>& rhs){
x=rhs.real();
y=rhs.imag();
z=0;
return *this;
}
inline const point_t<T>& operator=(const std::pair<T,T>& rhs){
x=rhs.first;
y=rhs.second;
z=0;
return *this;
}
inline const point_t<T>& operator=(const std::tuple<T,T,T>& rhs){
x=sget<0>(rhs);
y=sget<1>(rhs);
z=sget<2>(rhs);
return *this;
}
template<typename U>
inline constexpr bool operator==(point_t<U> cref rhs) const{
return (x==rhs.x)&&(y==rhs.y)&&(z==rhs.z);
}
template<typename U>
inline constexpr bool operator==(std::complex<U> cref rhs) const{
return (x==rhs.real())&&(y==rhs.imag())&&(z==*new value_type());
}
template<typename U>
inline constexpr bool operator==(U cref rhs) const{
return (U(x)==rhs)&&(y==*new value_type())&&(z==*new value_type());
}
};
template<typename T,typename U> inline constexpr i_eq(point_t<T>,point_t<U>)
template<typename T,typename U> inline constexpr i_eq(point_t<T>,U)
template<typename T,typename U> inline constexpr
i_eq(point_t<T>,std::complex<U>)
template<typename T,typename U> inline constexpr
bool operator==(T cref lhs,point_t<U> cref rhs){
return rhs==lhs;
}
template<typename T,typename U> inline constexpr
bool operator==(std::complex<T> lhs,point_t<U> rhs){
return rhs==lhs;
}
template<typename T, typename U> inline constexpr
i_not_eq(point_t<T>,point_t<U>)
template<typename T,typename U> inline constexpr i_not_eq(point_t<T>,U)
template<typename T,typename U> inline constexpr i_not_eq(T,point_t<U>)
template<typename T,typename U> inline constexpr
i_not_eq(point_t<T>,std::complex<U>)
template<typename T,typename U> inline constexpr
i_not_eq(std::complex<U>,point_t<T>)
typedef point_t<char> cpoint;
typedef point_t<schar> scpoint;
typedef point_t<uchar> ucpoint;
typedef point_t<sshort> spoint;
typedef point_t<ushort> uspoint;
typedef point_t<sint> point;
typedef point_t<uint> upoint;
typedef point_t<slong> lpoint;
typedef point_t<ulong> ulpoint;
typedef point_t<sllong> llpoint;
typedef point_t<ullong> ullpoint;
typedef point_t<float> fpoint,pointf;
typedef point_t<double> dpoint,pointd;
typedef point_t<ldouble> ldpoint, pointdl;
}
#endif //I14EXTRA_POINT_HPP
|
803d36c5f982e4a50a419106cb0837a43da31b28
|
dd80a584130ef1a0333429ba76c1cee0eb40df73
|
/external/chromium/chrome/browser/gpu_data_manager.cc
|
8fe42f03882a68f2bab50052caccd4ce543ba9d0
|
[
"BSD-3-Clause",
"MIT"
] |
permissive
|
karunmatharu/Android-4.4-Pay-by-Data
|
466f4e169ede13c5835424c78e8c30ce58f885c1
|
fcb778e92d4aad525ef7a995660580f948d40bc9
|
refs/heads/master
| 2021-03-24T13:33:01.721868
| 2017-02-18T17:48:49
| 2017-02-18T17:48:49
| 81,847,777
| 0
| 2
|
MIT
| 2020-03-09T00:02:12
| 2017-02-13T16:47:00
| null |
UTF-8
|
C++
| false
| false
| 7,680
|
cc
|
gpu_data_manager.cc
|
// Copyright (c) 2011 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/gpu_data_manager.h"
#include "base/command_line.h"
#include "base/metrics/histogram.h"
#include "base/string_number_conversions.h"
#include "chrome/common/child_process_logging.h"
#include "chrome/common/chrome_switches.h"
#include "content/browser/browser_thread.h"
#include "content/browser/gpu_blacklist.h"
#include "content/browser/gpu_process_host.h"
#include "content/common/gpu_messages.h"
#include "content/gpu/gpu_info_collector.h"
#include "ui/gfx/gl/gl_implementation.h"
#include "ui/gfx/gl/gl_switches.h"
GpuDataManager::GpuDataManager()
: complete_gpu_info_already_requested_(false) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
GPUInfo gpu_info;
gpu_info_collector::CollectPreliminaryGraphicsInfo(&gpu_info);
UpdateGpuInfo(gpu_info);
}
GpuDataManager::~GpuDataManager() { }
GpuDataManager* GpuDataManager::GetInstance() {
return Singleton<GpuDataManager>::get();
}
void GpuDataManager::RequestCompleteGpuInfoIfNeeded() {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
if (complete_gpu_info_already_requested_)
return;
complete_gpu_info_already_requested_ = true;
GpuProcessHost::SendOnIO(
0,
content::CAUSE_FOR_GPU_LAUNCH_GPUDATAMANAGER_REQUESTCOMPLETEGPUINFOIFNEEDED,
new GpuMsg_CollectGraphicsInfo());
}
void GpuDataManager::UpdateGpuInfo(const GPUInfo& gpu_info) {
base::AutoLock auto_lock(gpu_info_lock_);
if (!gpu_info_.Merge(gpu_info))
return;
child_process_logging::SetGpuInfo(gpu_info_);
}
const GPUInfo& GpuDataManager::gpu_info() const {
base::AutoLock auto_lock(gpu_info_lock_);
return gpu_info_;
}
Value* GpuDataManager::GetFeatureStatus() {
const CommandLine& browser_command_line = *CommandLine::ForCurrentProcess();
if (gpu_blacklist_.get())
return gpu_blacklist_->GetFeatureStatus(GpuAccessAllowed(),
browser_command_line.HasSwitch(switches::kDisableAcceleratedCompositing),
browser_command_line.HasSwitch(switches::kEnableAccelerated2dCanvas),
browser_command_line.HasSwitch(switches::kDisableExperimentalWebGL),
browser_command_line.HasSwitch(switches::kDisableGLMultisampling));
return NULL;
}
std::string GpuDataManager::GetBlacklistVersion() const {
if (gpu_blacklist_.get() != NULL) {
uint16 version_major, version_minor;
if (gpu_blacklist_->GetVersion(&version_major,
&version_minor)) {
std::string version_string =
base::UintToString(static_cast<unsigned>(version_major)) +
"." +
base::UintToString(static_cast<unsigned>(version_minor));
return version_string;
}
}
return "";
}
void GpuDataManager::AddLogMessage(Value* msg) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
log_messages_.Append(msg);
}
const ListValue& GpuDataManager::log_messages() const {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
return log_messages_;
}
GpuFeatureFlags GpuDataManager::GetGpuFeatureFlags() {
return gpu_feature_flags_;
}
bool GpuDataManager::GpuAccessAllowed() {
uint32 flags = gpu_feature_flags_.flags();
// This will in effect block access to all GPU features if any of them
// is blacklisted.
// TODO(vangelis): Restructure the code to make it possible to selectively
// blaclist gpu features.
return !(flags & GpuFeatureFlags::kGpuFeatureAccelerated2dCanvas ||
flags & GpuFeatureFlags::kGpuFeatureAcceleratedCompositing ||
flags & GpuFeatureFlags::kGpuFeatureWebgl);
}
void GpuDataManager::AddGpuInfoUpdateCallback(Callback0::Type* callback) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
gpu_info_update_callbacks_.insert(callback);
}
bool GpuDataManager::RemoveGpuInfoUpdateCallback(Callback0::Type* callback) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
std::set<Callback0::Type*>::iterator i =
gpu_info_update_callbacks_.find(callback);
if (i != gpu_info_update_callbacks_.end()) {
gpu_info_update_callbacks_.erase(i);
return true;
}
return false;
}
void GpuDataManager::AppendRendererCommandLine(
CommandLine* command_line) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
DCHECK(command_line);
uint32 flags = gpu_feature_flags_.flags();
if ((flags & GpuFeatureFlags::kGpuFeatureWebgl) &&
!command_line->HasSwitch(switches::kDisableExperimentalWebGL))
command_line->AppendSwitch(switches::kDisableExperimentalWebGL);
if ((flags & GpuFeatureFlags::kGpuFeatureMultisampling) &&
!command_line->HasSwitch(switches::kDisableGLMultisampling))
command_line->AppendSwitch(switches::kDisableGLMultisampling);
// If we have kGpuFeatureAcceleratedCompositing, we disable all GPU features.
if (flags & GpuFeatureFlags::kGpuFeatureAcceleratedCompositing) {
const char* switches[] = {
switches::kDisableAcceleratedCompositing,
switches::kDisableExperimentalWebGL
};
const int switch_count = sizeof(switches) / sizeof(char*);
for (int i = 0; i < switch_count; ++i) {
if (!command_line->HasSwitch(switches[i]))
command_line->AppendSwitch(switches[i]);
}
}
}
void GpuDataManager::UpdateGpuBlacklist(GpuBlacklist* gpu_blacklist) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
gpu_blacklist_.reset(gpu_blacklist);
UpdateGpuFeatureFlags();
}
void GpuDataManager::RunGpuInfoUpdateCallbacks() {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
std::set<Callback0::Type*>::iterator i = gpu_info_update_callbacks_.begin();
for (; i != gpu_info_update_callbacks_.end(); ++i) {
(*i)->Run();
}
}
void GpuDataManager::UpdateGpuFeatureFlags() {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
GpuBlacklist* gpu_blacklist = GetGpuBlacklist();
if (gpu_blacklist == NULL)
return;
// We don't set a lock around modifying gpu_feature_flags_ since it's just an
// int.
if (!gpu_blacklist) {
gpu_feature_flags_.set_flags(0);
return;
}
{
base::AutoLock auto_lock(gpu_info_lock_);
gpu_feature_flags_ = gpu_blacklist->DetermineGpuFeatureFlags(
GpuBlacklist::kOsAny, NULL, gpu_info_);
// If gpu is blacklisted, no further GPUInfo will be collected.
gpu_info_.finalized = true;
}
uint32 max_entry_id = gpu_blacklist->max_entry_id();
if (!gpu_feature_flags_.flags()) {
UMA_HISTOGRAM_ENUMERATION("GPU.BlacklistTestResultsPerEntry",
0, max_entry_id + 1);
return;
}
// Notify clients that GpuInfo state has changed
RunGpuInfoUpdateCallbacks();
// TODO(zmo): move histograming to GpuBlacklist::DetermineGpuFeatureFlags.
std::vector<uint32> flag_entries;
gpu_blacklist->GetGpuFeatureFlagEntries(
GpuFeatureFlags::kGpuFeatureAll, flag_entries);
DCHECK_GT(flag_entries.size(), 0u);
for (size_t i = 0; i < flag_entries.size(); ++i) {
UMA_HISTOGRAM_ENUMERATION("GPU.BlacklistTestResultsPerEntry",
flag_entries[i], max_entry_id + 1);
}
}
GpuBlacklist* GpuDataManager::GetGpuBlacklist() {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
const CommandLine& browser_command_line = *CommandLine::ForCurrentProcess();
if (browser_command_line.HasSwitch(switches::kIgnoreGpuBlacklist) ||
browser_command_line.GetSwitchValueASCII(
switches::kUseGL) == gfx::kGLImplementationOSMesaName)
return NULL;
// No need to return an empty blacklist.
if (gpu_blacklist_.get() != NULL && gpu_blacklist_->max_entry_id() == 0)
return NULL;
return gpu_blacklist_.get();
}
|
7fcff85fe33acf1c3c3eb161d62676214d13bb04
|
ab944ecbda508e51a544ab6d790ce1152dc10b93
|
/include/mogo.hpp
|
bfb8a67b1e9829ba0a8a20c1915788b23729fde6
|
[] |
no_license
|
Unionjackjz1/HW-DOGO-PROS
|
3f75104dbd7757a78c7d49b3d9f6da51fc47b54b
|
6ea3a5dc69f4e29754fbfc432df4db4ae0fa3c1c
|
refs/heads/main
| 2023-07-29T13:08:15.717634
| 2021-09-11T20:32:48
| 2021-09-11T20:32:48
| 392,468,524
| 2
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 280
|
hpp
|
mogo.hpp
|
#pragma once
extern bool mogo_up;
void set_mogo(int input);
void zero_mogo();
int get_mogo();
int get_mogo_vel();
void set_mogo_position(int target);
void mogo_in (bool hold = false);
void mogo_neut(bool hold = false);
void mogo_out (bool hold = false);
void mogo_control();
|
a7fadb6704d8c7e65cd20c1e7048d9a1e5b0561a
|
94ce8c482d9a1ecc28578b8986316961f03d2ea7
|
/CAScene.h
|
42117f8e1bd0db3dd22404d29ff4e2106cb25ac4
|
[] |
no_license
|
DavidDeSimone/ShadowPOC
|
ba507f746968d9f2dc4fd271205d999efaa62330
|
45d2aa6c38a2ba0b38661cdd03945fc1306d9241
|
refs/heads/master
| 2021-01-19T14:03:46.712526
| 2016-02-16T06:28:59
| 2016-02-16T06:28:59
| 52,418,973
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 831
|
h
|
CAScene.h
|
//
// CAScene.hpp
// ShadowPOC
//
// Created by David on 1/27/16.
// Copyright © 2016 David. All rights reserved.
//
#ifndef CAScene_hpp
#define CAScene_hpp
#include <stdio.h>
#include <vector>
class point_light;
class cube;
class quad;
class scene
{
public:
scene() = default;
~scene();
scene(scene&& mov) = delete;
scene(const scene& cpy) = delete;
std::vector<cube*>& get();
std::vector<point_light*>& get_point_lights();
std::vector<quad*>& get_quads();
void add(cube * cb);
void add(point_light * cl);
void add(quad * q);
void render(float dt) const;
void lighting_pass(float dt) const;
void renderq(float dt) const;
private:
std::vector<cube*> cvec;
std::vector<point_light*> clvec;
std::vector<quad*> qvec;
};
#endif /* CAScene_hpp */
|
a5f1a270edc42f566b5ff841eed6718bd097222a
|
11e19ecec57a85866aff96c5ecd57fd09cfc6b54
|
/WS02/lab/TimedEvents.cpp
|
b014d8b944e1dc7af37e8be87095604e7c8fe590
|
[] |
no_license
|
xiaozhuanli/OOP345-1
|
2789f080b8f8eea82eb633048a95a812f588509a
|
8da582b96588d08c3eb7b2d7493f687e5d0fc624
|
refs/heads/master
| 2022-04-15T09:20:47.422712
| 2020-04-12T04:31:29
| 2020-04-12T04:31:29
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,610
|
cpp
|
TimedEvents.cpp
|
// Name: Ricardo Maharaj
// Seneca Student ID: 160058186
// Seneca email: rmaharaj14@myseneca.ca
// Date of completion: 01/23/2020
//
// I confirm that the content of this file is created by me,
// with the exception of the parts provided to me by my professor.
#include "TimedEvents.h"
namespace sdds {
TimedEvents::TimedEvents() {
te_cur_recs = {0};
recs->te_name = {};
recs->te_time_unit = {};
recs->te_duration = {};
te_start_time = {};
te_end_time = {};
}
void TimedEvents::startClock() {
te_start_time = chrono::steady_clock::now();
}
void TimedEvents::stopClock() {
te_end_time = chrono::steady_clock::now();
}
void TimedEvents::recordEvent(const char *name) {
if (te_cur_recs < MAX_RECS) {
recs[te_cur_recs].te_name = name;
recs[te_cur_recs].te_time_unit = "nanoseconds";
recs[te_cur_recs].te_duration = chrono::duration_cast<chrono::nanoseconds>(te_end_time - te_start_time);
te_cur_recs++;
}
}
ostream &operator<<(ostream &os, const TimedEvents &te) {
os << "--------------------------\n";
os << "Execution Times:\n";
os << "--------------------------\n";
for (int i = 0; i < te.te_cur_recs; i++)
os << setw(20) << left
<< te.recs[i].te_name << ' '
<< setw(12) << right
<< te.recs[i].te_duration.count() << ' '
<< te.recs[i].te_time_unit << '\n';
os << "--------------------------\n";
return os;
}
}
|
22dc42283e07f88e7f9c205cd139d7885c40c990
|
ea85e7877278c10e94870e1d97130704ada3035c
|
/lib/condition.h
|
54c6cd4c3993a5993fc17a878e039a16f5289aeb
|
[] |
no_license
|
LBFing/Server
|
907bb11f472651faaa929239b08f702726466e01
|
084174a901d13e6b8488e4aca7e44d93dbb82f74
|
refs/heads/master
| 2021-10-18T23:08:00.463254
| 2019-02-15T03:16:19
| 2019-02-15T03:16:19
| 125,308,611
| 0
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 601
|
h
|
condition.h
|
#ifndef __CONDITION_H__
#define __CONDITION_H__
#include "nocopyable.h"
#include "type_define.h"
#include "mutex.h"
class Condition : private Nocopyable
{
public:
explicit Condition(Mutex& mutex) : m_mutex(mutex)
{
pthread_cond_init(&m_cond, nullptr);
}
~Condition()
{
pthread_cond_destroy(&m_cond);
}
void Wait()
{
Mutex::UnassignGuard ug(m_mutex);
pthread_cond_wait(&m_cond, m_mutex.GetPthreadMutex());
}
void Notify()
{
pthread_cond_signal(&m_cond);
}
void NotifyAll()
{
pthread_cond_broadcast(&m_cond);
}
private:
Mutex& m_mutex;
pthread_cond_t m_cond;
};
#endif
|
2210b580d5592a53fabe7cf0814b657a5af2b401
|
1f032ac06a2fc792859a57099e04d2b9bc43f387
|
/9c/2f/28/b5/db4ddf3cf860cfd555038df824c256887d39444bd485186f5f4807408c988952b1e80fcf827c49f35a5aef93b7cfb68d94ecc44c846382b0189c2242/sw.cpp
|
a1b2f59521309c83d7ee34cbfdfa0e765be63cfb
|
[] |
no_license
|
SoftwareNetwork/specifications
|
9d6d97c136d2b03af45669bad2bcb00fda9d2e26
|
ba960f416e4728a43aa3e41af16a7bdd82006ec3
|
refs/heads/master
| 2023-08-16T13:17:25.996674
| 2023-08-15T10:45:47
| 2023-08-15T10:45:47
| 145,738,888
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 158
|
cpp
|
sw.cpp
|
void build(Solution &s)
{
auto &t = s.addTarget<StaticLibrary>("fraillt.bitsery", "5.0.0");
t += Git("https://github.com/fraillt/bitsery", "v{v}");
}
|
1e83a06029093dff4f613d5cd7c8e7ad932bf9e6
|
c00f02cb63ae377032a15ab8a4c9282e21c2efaa
|
/OutlookImpExp/OutlookImporter.h
|
dc9f7fc084b1067b22e08b80c398ce183afb1f14
|
[] |
no_license
|
abstractspoon/ToDoList_7.0
|
90118dfccf8dddea4e1d9946f993afbcdcb8ef92
|
5ac02a54b1dc642442a451b58d28cc3c57efe739
|
refs/heads/master
| 2020-04-17T02:36:57.767662
| 2019-01-17T02:11:15
| 2019-01-17T02:11:15
| 166,143,975
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 984
|
h
|
OutlookImporter.h
|
// OutlookImporter.h: interface for the COutlookImporter class.
//
//////////////////////////////////////////////////////////////////////
#if !defined(AFX_OUTLOOKIMPORTER_H__C35841C7_32A6_4705_A061_24A85C3A0223__INCLUDED_)
#define AFX_OUTLOOKIMPORTER_H__C35841C7_32A6_4705_A061_24A85C3A0223__INCLUDED_
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
#include "..\Interfaces\IImportExport.h"
class ITransText;
class COutlookImporter : public IImportTasklist
{
public:
COutlookImporter();
virtual ~COutlookImporter();
void Release() { delete this; }
void SetLocalizer(ITransText* pTT);
LPCTSTR GetMenuText() const { return _T("Microsoft Outlook"); }
LPCTSTR GetFileFilter() const { return NULL; }
LPCTSTR GetFileExtension() const { return NULL; }
bool Import(LPCTSTR szSrcFilePath, ITaskList* pDestTaskFile, BOOL bSilent, IPreferences* pPrefs, LPCTSTR szKey);
};
#endif // !defined(AFX_OUTLOOKIMPORTER_H__C35841C7_32A6_4705_A061_24A85C3A0223__INCLUDED_)
|
3e17aada983c5b4b6d8699ecef8a9f85e7093fd3
|
21bdf55c29477befdcfa2eaaa176d73173f71983
|
/peer_server.h
|
582e7125e8e80296ddaf3ad238e2ba5ff48efb6d
|
[] |
no_license
|
jiang718/BulletinBoardConsistency
|
d140212599a0291cf581affcdde9b9fa17129a9f
|
098268d0c0d764bfc6a5ec91632ed7c2b39fec7e
|
refs/heads/master
| 2020-04-10T21:45:15.336929
| 2018-03-12T07:58:13
| 2018-03-12T07:58:13
| 124,295,859
| 0
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,676
|
h
|
peer_server.h
|
#ifndef PEER_SERVER_H
#define PEER_SERVER_H
#pragma once
#include <iostream>
#include <map>
#include <vector>
#include <set>
#include "article.h"
using namespace std;
class PeerServer {
string ip;
int port;
string coordinator_ip;
int coordinator_port;
ArticlePool articlePool;
int data;
int timeStamp;
set<pair<string, int>> serverList;
public:
//server pointer, whether is coordinator
PeerServer(string ip, int port);
PeerServer(string coordinator_ip, int coordinator_port, string ip, int port);
pair<string,int> chooseNewCoordinator();
pair<string,int> findCoordinator();
void printPeerServerList();
void printData();
set<pair<string,int>> getServerList();
bool isCoordinator();
bool isCoordinator(const pair<string,int> &ipAndPort);
void changeCoordinator(string coordinator_ip, int coordinator_port);
//------------------data replicas related function--------------//
void updateCoordinatorData(string origin_ip, int origin_port);
void updateFromServer(ArticlePool newData, string origin_ip, int origin_port);
void notifyDataChange(string origin_ip, int origin_port);
void notifyAllPeerServer(string origin_ip, int origin_port);
void updateSimple(ArticlePool newData);
//-------------------server list related functions-------------//
//store the peerServer into a simulated map, TODO
void joinNewServer(string server_ip, int server_port, PeerServer *p);
//join a server to server list based on whether this server is coordinator
void joinServer(string server_ip, int server_port);
//coordinator: add a new server to serverlist for all server
void joinServerToAll(string server_ip, int server_port);
//simply add a new server to serverlist
void joinServerSimple(string server_ip, int server_port);
//normal server: notify the coordinator that there's a new server
void notifyCoordinatorJoinServer(string server_ip, int server_port);
//delete a new server to serverlist for all server
void deleteServer(string server_ip, int server_port);
void deleteServerToAll(string server_ip, int server_port);
void deleteServerSimple(string server_ip, int server_port);
void notifyCoordinatorDeleteServer(string server_ip, int server_port);
//--------------------article related functions--------//
Article* choose(int index);
int reply(string article, int index);
int post(string article);
string read();
ArticlePool deepCopy();
//------------others----------------------//
int getTimeStamp();
void close();
};
//extern map<pair<string, int>, PeerServer*> simulateUDP;
#endif
|
c5d353387b6729cc6b7ab795e2d861b99eebcd62
|
436623ee85c9d9444d700b56f2729b12b9f2c659
|
/src/eepp/ui/uinodedrawable.cpp
|
bf9280639e3faf53f925b3fe575ec62860c128dc
|
[
"MIT"
] |
permissive
|
SpartanJ/eepp
|
0bd271b33058ef119f5c34460ed94e44df882a25
|
9f64a2149f3a0842ced34b8b981ffe3a8efc6d13
|
refs/heads/develop
| 2023-09-01T01:17:30.155540
| 2023-08-27T20:58:19
| 2023-08-27T20:58:19
| 125,767,856
| 341
| 27
|
MIT
| 2023-04-01T20:10:26
| 2018-03-18T21:11:21
|
C++
|
UTF-8
|
C++
| false
| false
| 18,636
|
cpp
|
uinodedrawable.cpp
|
#include <eepp/core/core.hpp>
#include <eepp/graphics/drawableresource.hpp>
#include <eepp/graphics/renderer/renderer.hpp>
#include <eepp/math/easing.hpp>
#include <eepp/system/functionstring.hpp>
#include <eepp/ui/css/stylesheetlength.hpp>
#include <eepp/ui/css/stylesheetspecification.hpp>
#include <eepp/ui/uinode.hpp>
#include <eepp/ui/uinodedrawable.hpp>
#include <eepp/ui/uiwidget.hpp>
using namespace EE::Math::easing;
namespace EE { namespace UI {
UINodeDrawable::Repeat UINodeDrawable::repeatFromText( const std::string& text ) {
if ( "repeat" == text )
return UINodeDrawable::Repeat::RepeatXY;
if ( "repeat-x" == text )
return UINodeDrawable::Repeat::RepeatX;
if ( "repeat-y" == text )
return UINodeDrawable::Repeat::RepeatY;
return UINodeDrawable::Repeat::NoRepeat;
}
UINodeDrawable* UINodeDrawable::New( UINode* owner ) {
return eeNew( UINodeDrawable, ( owner ) );
}
UINodeDrawable::UINodeDrawable( UINode* owner ) :
Drawable( Drawable::UINODEDRAWABLE ),
mOwner( owner ),
mBackgroundColor( owner ),
mNeedsUpdate( true ),
mClipEnabled( false ) {
mBackgroundColor.setColor( Color::Transparent );
}
UINodeDrawable::~UINodeDrawable() {
clearDrawables();
}
void UINodeDrawable::clearDrawables() {
for ( auto& drawable : mGroup ) {
eeDelete( drawable.second );
}
mGroup.clear();
mBackgroundColor.setColor( Color::Transparent );
}
void UINodeDrawable::setBorderRadius( const Uint32& radius ) {
mBackgroundColor.setRadius( radius );
}
Uint32 UINodeDrawable::getBorderRadius() const {
return mBackgroundColor.getRadius();
}
bool UINodeDrawable::layerExists( int index ) {
return mGroup.find( index ) != mGroup.end();
}
UINodeDrawable::LayerDrawable* UINodeDrawable::getLayer( int index ) {
auto it = mGroup.find( index );
if ( it == mGroup.end() )
mGroup[index] = UINodeDrawable::LayerDrawable::New( this );
return mGroup[index];
}
void UINodeDrawable::setDrawable( int index, Drawable* drawable, bool ownIt ) {
if ( drawable != getLayer( index )->getDrawable() ) {
getLayer( index )->setDrawable( drawable, ownIt );
}
}
void UINodeDrawable::setDrawable( int index, const std::string& drawable ) {
if ( drawable != getLayer( index )->getDrawableRef() ) {
getLayer( index )->setDrawable( drawable );
}
}
void UINodeDrawable::setDrawablePositionX( int index, const std::string& positionX ) {
getLayer( index )->setPositionX( positionX );
}
void UINodeDrawable::setDrawablePositionY( int index, const std::string& positionY ) {
getLayer( index )->setPositionY( positionY );
}
void UINodeDrawable::setDrawableRepeat( int index, const std::string& repeatRule ) {
getLayer( index )->setRepeat( repeatFromText( repeatRule ) );
for ( auto& layIt : mGroup ) {
if ( layIt.second->getRepeat() != Repeat::NoRepeat ) {
setClipEnabled( true );
break;
}
}
}
void UINodeDrawable::setDrawableSize( int index, const std::string& sizeEq ) {
getLayer( index )->setSizeEq( sizeEq );
}
void UINodeDrawable::setDrawableColor( int index, const Color& color ) {
getLayer( index )->setColor( color );
}
void UINodeDrawable::setBackgroundColor( const Color& color ) {
mBackgroundColor.setColor( color );
}
Color UINodeDrawable::getBackgroundColor() const {
return mBackgroundColor.getColor();
}
bool UINodeDrawable::getClipEnabled() const {
return mClipEnabled;
}
void UINodeDrawable::setClipEnabled( bool clipEnabled ) {
mClipEnabled = clipEnabled;
}
void UINodeDrawable::invalidate() {
mNeedsUpdate = true;
mBackgroundColor.invalidate();
}
UINode* UINodeDrawable::getOwner() const {
return mOwner;
}
UIBackgroundDrawable& UINodeDrawable::getBackgroundDrawable() {
return mBackgroundColor;
}
Sizef UINodeDrawable::getSize() {
return mSize;
}
Sizef UINodeDrawable::getPixelsSize() {
return mSize;
}
void UINodeDrawable::setSize( const Sizef& size ) {
if ( size != mSize ) {
mSize = size;
onSizeChange();
}
}
void UINodeDrawable::draw( const Vector2f& position, const Sizef& size ) {
draw( position, size, 255 );
}
void UINodeDrawable::draw( const Vector2f& position, const Sizef& size, const Uint32& alpha ) {
if ( position != mPosition ) {
mPosition = position;
invalidate();
}
if ( size != mSize ) {
mSize = size;
invalidate();
}
if ( mNeedsUpdate )
update();
if ( mClipEnabled )
GLi->getClippingMask()->clipPlaneEnable( mPosition.x, mPosition.y, mSize.x, mSize.y );
if ( mBackgroundColor.getColor().a != 0 ) {
if ( alpha != 255 ) {
Color color = mBackgroundColor.getColor();
mBackgroundColor.setAlpha( alpha * color.a / 255 );
mBackgroundColor.draw( position, size );
mBackgroundColor.setAlpha( color.a );
} else {
mBackgroundColor.draw( position, size );
}
}
bool masked = false;
ClippingMask* clippingMask = GLi->getClippingMask();
if ( !mGroup.empty() && mBackgroundColor.hasRadius() ) {
masked = true;
clippingMask->setMaskMode( ClippingMask::Inclusive );
clippingMask->clearMasks();
clippingMask->appendMask( mBackgroundColor );
clippingMask->stencilMaskEnable();
}
// Draw in reverse order to respect the background-image specification:
// "The background images are drawn on stacking context layers on top of each other. The first
// layer specified is drawn as if it is closest to the user."
for ( auto drawableIt = mGroup.rbegin(); drawableIt != mGroup.rend(); ++drawableIt ) {
UINodeDrawable::LayerDrawable* drawable = drawableIt->second;
if ( alpha != 255 ) {
Color color = drawable->getColor();
drawable->setAlpha( alpha * color.a / 255 );
drawable->draw( position, size );
drawable->setAlpha( color.a );
} else {
drawable->draw( position, size );
}
}
if ( masked ) {
clippingMask->stencilMaskDisable();
}
if ( mClipEnabled )
GLi->getClippingMask()->clipPlaneDisable();
}
void UINodeDrawable::draw( const Vector2f& position ) {
draw( position, mSize );
}
void UINodeDrawable::draw() {
draw( mPosition, mSize );
}
void UINodeDrawable::onPositionChange() {
invalidate();
}
void UINodeDrawable::onSizeChange() {
invalidate();
}
void UINodeDrawable::update() {
mBackgroundColor.setPosition( mPosition );
mBackgroundColor.setSize( mSize );
mNeedsUpdate = false;
}
/**** UINodeDrawable::LayerDrawable ****/
UINodeDrawable::LayerDrawable* UINodeDrawable::LayerDrawable::New( UINodeDrawable* container ) {
return eeNew( UINodeDrawable::LayerDrawable, ( container ) );
}
UINodeDrawable::LayerDrawable::LayerDrawable( UINodeDrawable* container ) :
Drawable( UINODEDRAWABLE_LAYERDRAWABLE ),
mContainer( container ),
mPositionX( "0px" ),
mPositionY( "0px" ),
mSizeEq( "auto" ),
mNeedsUpdate( false ),
mOwnsDrawable( false ),
mDrawable( NULL ),
mResourceChangeCbId( 0 ),
mRepeat( Repeat::NoRepeat ) {}
UINodeDrawable::LayerDrawable::~LayerDrawable() {
if ( NULL != mDrawable && 0 != mResourceChangeCbId && mDrawable->isDrawableResource() ) {
reinterpret_cast<DrawableResource*>( mDrawable )
->popResourceChangeCallback( mResourceChangeCbId );
}
if ( mOwnsDrawable )
eeSAFE_DELETE( mDrawable );
}
void UINodeDrawable::LayerDrawable::draw() {
draw( mPosition, mSize );
}
void UINodeDrawable::LayerDrawable::draw( const Vector2f& position ) {
draw( position, mSize );
}
static void repeatYdraw( Drawable* drawable, const Vector2f& position, const Vector2f& offset,
const Sizef& size, const Sizef& drawableSize ) {
if ( drawableSize.getHeight() > 0 ) {
Float startY = position.y + offset.y - drawableSize.getHeight();
while ( startY > position.y - drawableSize.getHeight() ) {
drawable->draw( Vector2f( position.x + offset.x, startY ), drawableSize );
startY -= drawableSize.getHeight();
};
drawable->draw( position + offset, drawableSize );
startY = position.y + offset.y + drawableSize.getHeight();
while ( startY < position.y + size.getHeight() ) {
drawable->draw( Vector2f( position.x + offset.x, startY ), drawableSize );
startY += drawableSize.getHeight();
};
}
}
void UINodeDrawable::LayerDrawable::draw( const Vector2f& position, const Sizef& size ) {
if ( position != mPosition ) {
mPosition = position;
invalidate();
}
if ( size != mSize ) {
mSize = size;
invalidate();
}
if ( mDrawable == NULL )
return;
if ( mNeedsUpdate )
update();
RGB prevColor = mDrawable->getColorFilter();
if ( mColorWasSet )
mDrawable->setColorFilter( getColor() );
mDrawable->setAlpha( getAlpha() );
switch ( mRepeat ) {
case Repeat::NoRepeat:
mDrawable->draw( mPosition + mOffset, mDrawableSize );
break;
case Repeat::RepeatX: {
if ( mDrawableSize.getWidth() > 0 ) {
Float startX = mPosition.x + mOffset.x - mDrawableSize.getWidth();
while ( startX > mPosition.x - mDrawableSize.getWidth() ) {
mDrawable->draw( Vector2f( startX, mPosition.y + mOffset.y ), mDrawableSize );
startX -= mDrawableSize.getWidth();
};
mDrawable->draw( mPosition + mOffset, mDrawableSize );
startX = mPosition.x + mOffset.x + mDrawableSize.getWidth();
while ( startX < mPosition.x + mSize.getWidth() ) {
mDrawable->draw( Vector2f( startX, mPosition.y + mOffset.y ), mDrawableSize );
startX += mDrawableSize.getWidth();
};
}
break;
}
case Repeat::RepeatY: {
repeatYdraw( mDrawable, mPosition, mOffset, mSize, mDrawableSize );
break;
}
case Repeat::RepeatXY: {
if ( mDrawableSize.getWidth() > 0 ) {
Float startX = mPosition.x + mOffset.x - mDrawableSize.getWidth();
while ( startX > mPosition.x - mDrawableSize.getWidth() ) {
repeatYdraw( mDrawable, mPosition, Vector2f( startX - mPosition.x, mOffset.y ),
mSize, mDrawableSize );
startX -= mDrawableSize.getWidth();
};
repeatYdraw( mDrawable, mPosition, mOffset, mSize, mDrawableSize );
startX = mPosition.x + mOffset.x + mDrawableSize.getWidth();
while ( startX < mPosition.x + mSize.getWidth() ) {
repeatYdraw( mDrawable, mPosition, Vector2f( startX - mPosition.x, mOffset.y ),
mSize, mDrawableSize );
startX += mDrawableSize.getWidth();
};
}
break;
}
}
if ( mColorWasSet )
mDrawable->setColorFilter( prevColor );
}
Sizef UINodeDrawable::LayerDrawable::getSize() {
return mSize;
}
Sizef UINodeDrawable::LayerDrawable::getPixelsSize() {
return mSize;
}
void UINodeDrawable::LayerDrawable::setSize( const Sizef& size ) {
if ( size != mSize ) {
mSize = size;
invalidate();
}
}
Drawable* UINodeDrawable::LayerDrawable::getDrawable() const {
return mDrawable;
}
const std::string& UINodeDrawable::LayerDrawable::getDrawableRef() const {
return mDrawableRef;
}
void UINodeDrawable::LayerDrawable::setDrawable( Drawable* drawable, const bool& ownIt ) {
if ( drawable == mDrawable )
return;
if ( NULL != mDrawable ) {
if ( mDrawable->isDrawableResource() ) {
reinterpret_cast<DrawableResource*>( mDrawable )
->popResourceChangeCallback( mResourceChangeCbId );
}
if ( mOwnsDrawable ) {
eeSAFE_DELETE( mDrawable );
}
}
mDrawable = drawable;
mDrawableRef = "";
mOwnsDrawable = ownIt;
invalidate();
if ( NULL != mDrawable && mDrawable->isDrawableResource() ) {
mResourceChangeCbId = reinterpret_cast<DrawableResource*>( mDrawable )
->pushResourceChangeCallback(
[this]( DrawableResource::Event event, DrawableResource* ) {
invalidate();
if ( event == DrawableResource::Event::Unload ) {
mResourceChangeCbId = 0;
mDrawable = NULL;
mOwnsDrawable = false;
}
} );
}
}
void UINodeDrawable::LayerDrawable::setDrawable( const std::string& drawableRef ) {
bool ownIt;
Drawable* drawable = createDrawable( drawableRef, mSize, ownIt );
setDrawable( drawable, ownIt );
mDrawableRef = drawableRef;
}
Drawable* UINodeDrawable::LayerDrawable::createDrawable( const std::string& value,
const Sizef& size, bool& ownIt ) {
return CSS::StyleSheetSpecification::instance()->getDrawableImageParser().createDrawable(
value, size, ownIt, mContainer->getOwner() );
}
const Vector2f& UINodeDrawable::LayerDrawable::getOffset() const {
if ( mNeedsUpdate )
const_cast<LayerDrawable*>( this )->update();
return mOffset;
}
const UINodeDrawable::Repeat& UINodeDrawable::LayerDrawable::getRepeat() const {
return mRepeat;
}
void UINodeDrawable::LayerDrawable::setRepeat( const UINodeDrawable::Repeat& repeat ) {
if ( mRepeat != repeat ) {
mRepeat = repeat;
invalidate();
}
}
void UINodeDrawable::LayerDrawable::invalidate() {
mNeedsUpdate = true;
}
const Sizef& UINodeDrawable::LayerDrawable::getDrawableSize() const {
if ( mNeedsUpdate )
const_cast<LayerDrawable*>( this )->update();
return mDrawableSize;
}
void UINodeDrawable::LayerDrawable::setDrawableSize( const Sizef& drawableSize ) {
mDrawableSize = drawableSize;
}
Sizef UINodeDrawable::LayerDrawable::calcDrawableSize( const std::string& drawableSizeEq ) {
Sizef size;
if ( NULL == mDrawable )
return Sizef::Zero;
if ( drawableSizeEq == "auto" ) {
if ( mDrawable->getDrawableType() == Drawable::RECTANGLE ) {
size = mSize;
} else {
size = mDrawable->getSize();
}
} else if ( drawableSizeEq == "expand" ) {
size = mSize;
} else if ( drawableSizeEq == "contain" ) {
Sizef drawableSize( mDrawable->getSize() );
Float Scale1 = mSize.getWidth() / drawableSize.getWidth();
Float Scale2 = mSize.getHeight() / drawableSize.getHeight();
if ( Scale1 < 1 || Scale2 < 1 ) {
Scale1 = eemin( Scale1, Scale2 );
size = Sizef( drawableSize.getWidth() * Scale1, drawableSize.getHeight() * Scale1 );
} else {
size = drawableSize;
}
} else if ( drawableSizeEq == "cover" ) {
Sizef drawableSize( mDrawable->getSize() );
Float Scale1 = mSize.getWidth() / drawableSize.getWidth();
Float Scale2 = mSize.getHeight() / drawableSize.getHeight();
Scale1 = eemax( Scale1, Scale2 );
size = Sizef( drawableSize.getWidth() * Scale1, drawableSize.getHeight() * Scale1 );
} else {
std::vector<std::string> sizePart = String::split( drawableSizeEq, ' ' );
if ( sizePart.size() == 1 ) {
sizePart.push_back( "auto" );
}
if ( sizePart.size() == 2 ) {
if ( sizePart[0] == "auto" && sizePart[1] == "auto" ) {
if ( mDrawable->getDrawableType() == Drawable::RECTANGLE ) {
size = mSize;
} else {
size = mDrawable->getSize();
}
} else if ( sizePart[0] != "auto" ) {
CSS::StyleSheetLength wl( sizePart[0] );
size.x = mContainer->getOwner()->convertLength(
wl, mContainer->getOwner()->getPixelsSize().getWidth() );
if ( sizePart[1] == "auto" ) {
Sizef drawableSize( mDrawable->getSize() );
size.y =
drawableSize.getHeight() * ( size.getWidth() / drawableSize.getWidth() );
} else {
CSS::StyleSheetLength hl( sizePart[1] );
size.y = mContainer->getOwner()->convertLength(
hl, mContainer->getOwner()->getPixelsSize().getHeight() );
}
} else {
CSS::StyleSheetLength hl( sizePart[1] );
size.y = mContainer->getOwner()->convertLength(
hl, mContainer->getOwner()->getPixelsSize().getHeight() );
Sizef drawableSize( mDrawable->getSize() );
size.x = drawableSize.getWidth() * ( size.getHeight() / drawableSize.getHeight() );
}
}
}
return size;
}
Vector2f UINodeDrawable::LayerDrawable::calcPosition( const std::string& positionEq ) {
Vector2f position( Vector2f::Zero );
std::vector<std::string> pos = String::split( positionEq, ' ' );
if ( pos.size() == 1 )
pos.push_back( "center" );
if ( pos.size() == 2 ) {
int xFloatIndex = 0;
int yFloatIndex = 1;
if ( "bottom" == pos[0] || "top" == pos[0] ) {
xFloatIndex = 1;
yFloatIndex = 0;
}
CSS::StyleSheetLength xl( pos[xFloatIndex] );
CSS::StyleSheetLength yl( pos[yFloatIndex] );
position.x = mContainer->getOwner()->convertLength(
xl, mContainer->getOwner()->getPixelsSize().getWidth() - mDrawableSize.getWidth() );
position.y = mContainer->getOwner()->convertLength(
yl, mContainer->getOwner()->getPixelsSize().getHeight() - mDrawableSize.getHeight() );
} else if ( pos.size() > 2 ) {
if ( pos.size() == 3 ) {
pos.push_back( "0dp" );
}
int xFloatIndex = 0;
int yFloatIndex = 2;
if ( "bottom" == pos[0] || "top" == pos[0] ) {
xFloatIndex = 2;
yFloatIndex = 0;
}
CSS::StyleSheetLength xl1( pos[xFloatIndex] );
CSS::StyleSheetLength xl2( pos[xFloatIndex + 1] );
CSS::StyleSheetLength yl1( pos[yFloatIndex] );
CSS::StyleSheetLength yl2( pos[yFloatIndex + 1] );
position.x = mContainer->getOwner()->convertLength(
xl1, mContainer->getOwner()->getPixelsSize().getWidth() - mDrawableSize.getWidth() );
Float xl2Val = mContainer->getOwner()->convertLength(
xl2, mContainer->getOwner()->getPixelsSize().getWidth() - mDrawableSize.getWidth() );
position.x += ( pos[xFloatIndex] == "right" ) ? -xl2Val : xl2Val;
position.y = mContainer->getOwner()->convertLength(
yl1, mContainer->getOwner()->getPixelsSize().getWidth() - mDrawableSize.getHeight() );
Float yl2Val = mContainer->getOwner()->convertLength(
yl2, mContainer->getOwner()->getPixelsSize().getWidth() - mDrawableSize.getHeight() );
position.y += ( pos[yFloatIndex] == "bottom" ) ? -yl2Val : yl2Val;
}
return position;
}
const std::string& UINodeDrawable::LayerDrawable::getSizeEq() const {
return mSizeEq;
}
void UINodeDrawable::LayerDrawable::setSizeEq( const std::string& sizeEq ) {
if ( mSizeEq != sizeEq ) {
mSizeEq = sizeEq;
invalidate();
}
}
const std::string& UINodeDrawable::LayerDrawable::getPositionY() const {
return mPositionY;
}
void UINodeDrawable::LayerDrawable::setPositionY( const std::string& positionY ) {
if ( mPositionY != positionY ) {
mPositionY = positionY;
invalidate();
}
}
const std::string& UINodeDrawable::LayerDrawable::getPositionX() const {
return mPositionX;
}
void UINodeDrawable::LayerDrawable::setPositionX( const std::string& positionX ) {
if ( mPositionX != positionX ) {
mPositionX = positionX;
invalidate();
}
}
void UINodeDrawable::LayerDrawable::setOffset( const Vector2f& offset ) {
mOffset = offset;
}
std::string UINodeDrawable::LayerDrawable::getOffsetEq() {
return String::fromFloat( mOffset.x, "px" ) + " " + String::fromFloat( mOffset.y, "px" );
}
void UINodeDrawable::LayerDrawable::onPositionChange() {
invalidate();
}
void UINodeDrawable::LayerDrawable::onColorFilterChange() {
mColorWasSet = true;
invalidate();
}
void UINodeDrawable::LayerDrawable::update() {
if ( mDrawable == NULL )
return;
if ( !mDrawableRef.empty() ) {
setDrawable( mDrawableRef );
}
mDrawableSize = calcDrawableSize( mSizeEq );
mOffset = calcPosition( mPositionX + " " + mPositionY );
mNeedsUpdate = false;
}
}} // namespace EE::UI
|
3f675bb02f608b032ea70ca699bfb08ca3d3144a
|
d5a81a9c8c453df01040c13f5a735c3913f4ea87
|
/objects/Camera.cpp
|
9db68003508f6cf1309f8f5e41884da508ab98a1
|
[] |
no_license
|
mrate/LAE
|
69fa1359f346d87e62eae5f4406e27925730a1f1
|
d92ffa186ca0bd5126f4b338e591bfa8449cfffc
|
refs/heads/master
| 2021-01-21T01:33:19.181014
| 2015-02-04T22:56:11
| 2015-02-04T22:56:11
| 101,878,935
| 5
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,575
|
cpp
|
Camera.cpp
|
// LAE
#include "Camera.h"
#include "../logger/Logger.h"
#include "../game/Global.h"
// stl
#include <math.h>
namespace LAE {
Camera::Camera()
: x_( 0 )
, y_( 0 )
, width_( 0 )
, height( 0 )
, tx_( 0 )
, ty_( 0 )
, speed_( 5 )
, followType_( C_IDLE )
, sprite_( nullptr )
, actor_( nullptr ) {
}
Camera::~Camera() {
}
void Camera::fastForward() {
if( followType_ != C_MOVE_TO ) {
return;
}
followType_ = C_IDLE;
x_ = tx_ - Global::i()->screenWidth() / 2;
y_ = ty_ - Global::i()->screenHeight() / 2;
}
void Camera::update( unsigned long time ) {
double dx;
double dy;
double lx = x_;
double ly = y_;
switch( followType_ ) {
case C_IDLE:
dx = x_;
dy = y_;
break;
case C_MOVE_TO:
dx = tx_ - Global::i()->screenWidth() / 2;
dy = ty_ - Global::i()->screenHeight() / 2;
break;
case C_FOLLOW_ACTOR:
dx = actor_->getX() - Global::i()->screenWidth() / 2;
dy = actor_->getY() - Global::i()->screenHeight() / 2;
break;
case C_FOLLOW_SPRITE:
dx = sprite_->getX() - Global::i()->screenWidth() / 2;
dy = sprite_->getY() - Global::i()->screenHeight() / 2;
break;
}
checkBorders( dx, dy );
double angle = ( double )atan2( ( double )( dx - x_ ), ( double )( dy - y_ ) );
double delta = ( ( double )time / ( double )speed_ );
x_ += sin( angle ) * delta;
y_ += cos( angle ) * delta;
if( ( sgn( lx - dx ) != sgn( x_ - dx ) )
|| ( sgn( ly - dy ) != sgn( y_ - dy ) ) ) {
x_ = dx;
y_ = dy;
if( followType_ == C_MOVE_TO ) {
followType_ = C_IDLE;
}
}
}
bool Camera::isIdle() const {
return followType_ == C_IDLE;
}
void Camera::follow( Actor* act ) {
followType_ = C_FOLLOW_ACTOR;
actor_ = act;
}
void Camera::follow( Sprite* spr ) {
followType_ = C_FOLLOW_SPRITE;
sprite_ = spr;
}
void Camera::setPos( int x, int y ) {
followType_ = C_IDLE;
this->x_ = x;
this->y_ = y;
}
void Camera::moveTo( int x, int y ) {
LOG_DEBUG( "camera_moveto " << x << ", " << y );
followType_ = C_MOVE_TO;
tx_ = x;
ty_ = y;
}
void Camera::focusOnItem( Item* item ) {
moveTo( item->getX(), item->getY() );
}
void Camera::setBorders( int w, int h ) {
width_ = w;
height = h;
checkBorders( x_, y_ );
}
void Camera::checkBorders( double& px, double& py ) {
if( px + Global::i()->screenWidth() > width_ ) {
px = width_ - Global::i()->screenWidth();
}
if( py + Global::i()->screenHeight() > height ) {
py = height - Global::i()->screenHeight();
}
if( px < 0 ) {
px = 0;
}
if( py < 0 ) {
py = 0;
}
}
int Camera::getX() const {
return ( int )x_;
}
int Camera::getY() const {
return ( int )y_;
}
}
|
1201490922c315d6bc55a8b90515d6c60e52796c
|
b258e2449fd26ab92c4be56a368e45c514efe60a
|
/settingpage.h
|
e91f0371fcb18f137878b03dfde7ac1cdc71aa3e
|
[] |
no_license
|
MinnieJewel/DJY
|
f6c3e6b99104f334fa41f98d6c5256352ff6fad8
|
74a3b6b34871a7fbd38b9fc0d8158b679d54014a
|
refs/heads/master
| 2022-09-16T19:30:46.147808
| 2020-06-02T06:29:42
| 2020-06-02T06:29:42
| 268,722,025
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 402
|
h
|
settingpage.h
|
#ifndef SETTINGPAGE_H
#define SETTINGPAGE_H
#include "mybase.h"
class QButtonGroup;
class QLabel;
namespace Ui {
class SettingPage;
}
class SettingPage : public MyBase
{
Q_OBJECT
public:
explicit SettingPage(QWidget *parent = 0);
~SettingPage();
QButtonGroup *setGroup;
private slots:
void onNumberClicked(int);
private:
Ui::SettingPage *ui;
};
#endif // SETTINGPAGE_H
|
d00eef2441c5ec0a6af0df67f11235c08afa0cba
|
575ca59de0445406bae1cbfc269ca78aabd2b880
|
/DragAndDropWindow/DrangAndDropWindow/DrangAndDropWindowView.cpp
|
f24f9de6fa1ec614ca8c5d4d5605fcefeb9fcb31
|
[] |
no_license
|
kwansu/MFC_Practice
|
5a1bdeaea86a0452be306cebf4747d6c44e361d8
|
9562c6a9b74b4e0f6ec85dcd9df626083e27ae1f
|
refs/heads/main
| 2023-04-28T01:31:55.699285
| 2021-05-16T03:30:32
| 2021-05-16T03:30:32
| 367,356,635
| 0
| 0
| null | null | null | null |
UHC
|
C++
| false
| false
| 3,932
|
cpp
|
DrangAndDropWindowView.cpp
|
// DrangAndDropWindowView.cpp : CDrangAndDropWindowView 클래스의 구현
//
#include "stdafx.h"
// SHARED_HANDLERS는 미리 보기, 축소판 그림 및 검색 필터 처리기를 구현하는 ATL 프로젝트에서 정의할 수 있으며
// 해당 프로젝트와 문서 코드를 공유하도록 해 줍니다.
#ifndef SHARED_HANDLERS
#include "DrangAndDropWindow.h"
#endif
#include "DrangAndDropWindowDoc.h"
#include "DrangAndDropWindowView.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#endif
// CDrangAndDropWindowView
IMPLEMENT_DYNCREATE(CDrangAndDropWindowView, CView)
BEGIN_MESSAGE_MAP(CDrangAndDropWindowView, CView)
// 표준 인쇄 명령입니다.
ON_COMMAND(ID_FILE_PRINT, &CView::OnFilePrint)
ON_COMMAND(ID_FILE_PRINT_DIRECT, &CView::OnFilePrint)
ON_COMMAND(ID_FILE_PRINT_PREVIEW, &CView::OnFilePrintPreview)
ON_WM_MOUSEMOVE()
ON_WM_LBUTTONDOWN()
ON_WM_LBUTTONUP()
ON_WM_NCHITTEST()
ON_WM_CREATE()
END_MESSAGE_MAP()
// CDrangAndDropWindowView 생성/소멸
CDrangAndDropWindowView::CDrangAndDropWindowView()
{
}
CDrangAndDropWindowView::~CDrangAndDropWindowView()
{
}
BOOL CDrangAndDropWindowView::PreCreateWindow(CREATESTRUCT& cs)
{
// TODO: CREATESTRUCT cs를 수정하여 여기에서
// Window 클래스 또는 스타일을 수정합니다.
return CView::PreCreateWindow(cs);
}
// CDrangAndDropWindowView 그리기
void CDrangAndDropWindowView::OnDraw(CDC* /*pDC*/)
{
CDrangAndDropWindowDoc* pDoc = GetDocument();
ASSERT_VALID(pDoc);
if (!pDoc)
return;
// TODO: 여기에 원시 데이터에 대한 그리기 코드를 추가합니다.
}
// CDrangAndDropWindowView 인쇄
BOOL CDrangAndDropWindowView::OnPreparePrinting(CPrintInfo* pInfo)
{
// 기본적인 준비
return DoPreparePrinting(pInfo);
}
void CDrangAndDropWindowView::OnBeginPrinting(CDC* /*pDC*/, CPrintInfo* /*pInfo*/)
{
// TODO: 인쇄하기 전에 추가 초기화 작업을 추가합니다.
}
void CDrangAndDropWindowView::OnEndPrinting(CDC* /*pDC*/, CPrintInfo* /*pInfo*/)
{
// TODO: 인쇄 후 정리 작업을 추가합니다.
}
// CDrangAndDropWindowView 진단
#ifdef _DEBUG
void CDrangAndDropWindowView::AssertValid() const
{
CView::AssertValid();
}
void CDrangAndDropWindowView::Dump(CDumpContext& dc) const
{
CView::Dump(dc);
}
CDrangAndDropWindowDoc* CDrangAndDropWindowView::GetDocument() const // 디버그되지 않은 버전은 인라인으로 지정됩니다.
{
ASSERT(m_pDocument->IsKindOf(RUNTIME_CLASS(CDrangAndDropWindowDoc)));
return (CDrangAndDropWindowDoc*)m_pDocument;
}
#endif //_DEBUG
// CDrangAndDropWindowView 메시지 처리기
void CDrangAndDropWindowView::OnMouseMove(UINT nFlags, CPoint point)
{
if (m_bDragFlag)
{
ClientToScreen(&point);
CPoint ptNewPos = point + m_ptMousePos;
CString str;
str.Format(_T("%d, %d"), ptNewPos.x, ptNewPos.y);
m_pFrameWnd->SetWindowText(str);
m_pFrameWnd->SetWindowPos(&CWnd::wndTop, ptNewPos.x
, ptNewPos.y, 0, 0, SWP_SHOWWINDOW | SWP_NOSIZE | SWP_NOZORDER);
}
CView::OnMouseMove(nFlags, point);
}
void CDrangAndDropWindowView::OnLButtonDown(UINT nFlags, CPoint point)
{
ClientToScreen(&point);
m_pFrameWnd->GetWindowRect(&m_rtFrameWnd);
m_ptMousePos = CPoint(m_rtFrameWnd.left, m_rtFrameWnd.top) - point;
m_bDragFlag = TRUE;
CView::OnLButtonDown(nFlags, point);
}
void CDrangAndDropWindowView::OnLButtonUp(UINT nFlags, CPoint point)
{
if (m_bDragFlag)
m_bDragFlag = FALSE;
CView::OnLButtonUp(nFlags, point);
}
LRESULT CDrangAndDropWindowView::OnNcHitTest(CPoint point)
{
return CView::OnNcHitTest(point);
}
int CDrangAndDropWindowView::OnCreate(LPCREATESTRUCT lpCreateStruct)
{
if (CView::OnCreate(lpCreateStruct) == -1)
return -1;
m_pFrameWnd = AFXGetParentFrame(this);
m_bDragFlag = FALSE;
return 0;
}
|
d35e2c2e13ff1af353901e8695be2f05624f82fd
|
9bb0fcb4123107483c79fdee2d9f13b95ef02148
|
/cpp/analyzer/test.cpp
|
fab80c15c611087d334d718c80dbf398b7e61c3e
|
[
"BSD-2-Clause"
] |
permissive
|
cksystemsgroup/zeta
|
0080d20918a8f12e431d2cd99c4968bbb331f32f
|
ae31ee583556f7c3305daf7a41401aafb4557eb6
|
refs/heads/master
| 2020-04-09T05:46:21.703149
| 2013-07-19T11:35:08
| 2013-07-19T11:35:08
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 13,291
|
cpp
|
test.cpp
|
// Please see the AUTHORS file for details. Use of this source code is governed
// by a BSD license that can be found in the LICENSE file.
#define __STDC_FORMAT_MACROS
#include <stdio.h>
#include "operation.h"
#include "parser.h"
#include "linearizer.h"
#include <stdlib.h>
#include <time.h>
#include <assert.h>
#include <string.h>
#include "analyzer.h"
void print_op(Operation* op) {
assert(op != NULL);
if (op->type() == Operation::INSERT) {
printf("+ %"PRId64" %"PRIu64"\n", op->value(), op->start());
} else {
printf("- %"PRId64" %"PRIu64"\n", op->value(), op->start());
}
}
void test_selectable_remove() {
Operation i1, i2, i3, i4, r1, r2, r3, r4;
const int num_ops = 8;
Operation* ops[num_ops] = {
&i1
, &r1
, &i2
, &r2
, &i3
, &r3
, &i4
, &r4
};
i1.initialize( 1, 0, 2, Operation::INSERT, 1);
i2.initialize( 3, 0, 4, Operation::INSERT, 2);
i3.initialize( 5, 0, 6, Operation::INSERT, 3);
i4.initialize( 7, 0, 8, Operation::INSERT, 4);
r4.initialize( 9, 0, 11, Operation::REMOVE, 4);
r3.initialize(10, 0, 16, Operation::REMOVE, 3);
r1.initialize(12, 0, 13, Operation::REMOVE, 1);
r2.initialize(14, 0, 15, Operation::REMOVE, 2);
Order** linearization;
linearization = linearize_by_min_sum(ops, num_ops, linearize_by_invocation(ops, num_ops));
assert (linearization[0]->operation == &i1);
assert (linearization[1]->operation == &i2);
assert (linearization[2]->operation == &i3);
assert (linearization[3]->operation == &i4);
assert (linearization[4]->operation == &r4);
assert (linearization[5]->operation == &r1);
assert (linearization[6]->operation == &r2);
assert (linearization[7]->operation == &r3);
printf("%s passed!\n", __func__);
}
void test_max_dev_null_return() {
Operation i1, i2, r1, r2, n1;
const int num_ops = 5;
Operation* ops[num_ops] = {
&i1
, &r1
, &n1
, &i2
, &r2
};
i1.initialize( 1, 0, 3, Operation::INSERT, 1);
i2.initialize( 2, 0, 5, Operation::INSERT, 2);
n1.initialize( 4, 0, 6, Operation::REMOVE, -1);
r2.initialize( 7, 0, 8, Operation::REMOVE, 2);
r1.initialize( 9, 0, 10, Operation::REMOVE, 1);
Order** linearization;
linearization = linearize_by_min_max(ops, num_ops);
assert (linearization[0]->operation == &i2);
assert (linearization[1]->operation == &i1);
assert (linearization[2]->operation == &n1);
assert (linearization[3]->operation == &r2);
assert (linearization[4]->operation == &r1);
printf("%s passed!\n", __func__);
}
void test_selectable_insert() {
Operation i1, i2, r1, r2, n1;
const int num_ops = 5;
Operation* ops[num_ops] = {
&i1
, &r1
, &n1
, &i2
, &r2
};
i1.initialize( 1, 0, 9, Operation::INSERT, 1);
i2.initialize( 2, 0, 3, Operation::INSERT, 2);
r1.initialize( 4, 0, 5, Operation::REMOVE, 1);
r2.initialize( 6, 0, 7, Operation::REMOVE, 2);
n1.initialize( 8, 0, 10, Operation::REMOVE, -1);
Order** linearization;
linearization = linearize_by_min_sum(ops, num_ops, linearize_by_invocation(ops, num_ops));
assert (linearization[0]->operation == &i1);
assert (linearization[1]->operation == &i2);
assert (linearization[2]->operation == &r1);
assert (linearization[3]->operation == &r2);
assert (linearization[4]->operation == &n1);
printf("%s passed!\n", __func__);
}
void test_equal_time_stamp_max() {
Operation i1, i2, r1, r2, n1;
const int num_ops = 5;
Operation* ops[num_ops] = {
&i1
, &r1
, &n1
, &i2
, &r2
};
i1.initialize( 1, 0, 2, Operation::INSERT, 1);
n1.initialize( 2, 0, 4, Operation::REMOVE, -1);
r1.initialize( 3, 0, 5, Operation::REMOVE, 1);
i2.initialize( 6, 0, 7, Operation::INSERT, 2);
r2.initialize( 8, 0, 9, Operation::REMOVE, 2);
Order** linearization;
linearization = linearize_by_min_max(ops, num_ops);
assert (linearization[0]->operation == &n1);
assert (linearization[1]->operation == &i1);
assert (linearization[2]->operation == &r1);
assert (linearization[3]->operation == &i2);
assert (linearization[4]->operation == &r2);
printf("%s passed!\n", __func__);
}
void test_equal_time_stamp_sum() {
Operation i1, i2, r1, r2, n1;
const int num_ops = 5;
Operation* ops[num_ops] = {
&i1
, &r1
, &n1
, &i2
, &r2
};
i1.initialize( 1, 0, 2, Operation::INSERT, 1);
n1.initialize( 2, 0, 4, Operation::REMOVE, -1);
r1.initialize( 3, 0, 5, Operation::REMOVE, 1);
i2.initialize( 6, 0, 7, Operation::INSERT, 2);
r2.initialize( 8, 0, 9, Operation::REMOVE, 2);
Order** linearization;
linearization = linearize_by_min_sum(ops, num_ops, linearize_by_invocation(ops, num_ops));
assert (linearization[0]->operation == &n1);
assert (linearization[1]->operation == &i1);
assert (linearization[2]->operation == &r1);
assert (linearization[3]->operation == &i2);
assert (linearization[4]->operation == &r2);
printf("%s passed!\n", __func__);
}
void test_null_return1() {
Operation i1, i2, r1, r2, n1;
const int num_ops = 5;
Operation* ops[num_ops] = {
&i1
, &r1
, &n1
, &i2
, &r2
};
i1.initialize(1, 0, 2, Operation::INSERT, 1);
n1.initialize(3, 0, 10, Operation::REMOVE, -1);
i2.initialize(4, 0, 5, Operation::INSERT, 2);
r1.initialize(6, 0, 7, Operation::REMOVE, 1);
r2.initialize(8, 0, 9, Operation::REMOVE, 2);
Order** linearization;
linearization = linearize_by_min_max(ops, num_ops);
assert (linearization[0]->operation == &i1);
assert (linearization[1]->operation == &i2);
assert (linearization[2]->operation == &r1);
assert (linearization[3]->operation == &r2);
assert (linearization[4]->operation == &n1);
printf("%s passed!\n", __func__);
}
void test_null_return2() {
Operation i1, i2, i3, r1, r2, r3, n1;
const int num_ops = 7;
Operation* ops[num_ops] = {
&i1
, &r1
, &n1
, &i2
, &r2
, &i3
, &r3
};
r1.initialize( 1, 0, 14, Operation::REMOVE, 1);
i2.initialize( 2, 0, 13, Operation::INSERT, 2);
n1.initialize( 3, 0, 10, Operation::REMOVE, -1);
i3.initialize( 4, 0, 5 , Operation::INSERT, 3);
i1.initialize( 6, 0, 7 , Operation::INSERT, 1);
r2.initialize( 8, 0, 9 , Operation::REMOVE, 2);
r3.initialize(11, 0, 12, Operation::REMOVE, 3);
Order** linearization;
linearization = linearize_by_min_max(ops, num_ops);
assert (linearization[0]->operation == &n1);
assert (linearization[1]->operation == &i2);
assert (linearization[2]->operation == &i3);
assert (linearization[3]->operation == &i1);
assert (linearization[4]->operation == &r2);
assert (linearization[5]->operation == &r3);
assert (linearization[6]->operation == &r1);
printf("%s passed!\n", __func__);
}
void test_null_return3() {
Operation i1, i2, i3, i4, i5, r1, r2, r3, r4, r5, n1;
const int num_ops = 11;
Operation* ops[num_ops] = {
&i1
, &r1
, &n1
, &i2
, &r2
, &i3
, &r3
, &i4
, &r4
, &i5
, &r5
};
i4.initialize( 2, 0, 4, Operation::INSERT, 4);
i5.initialize( 6, 0, 8, Operation::INSERT, 5);
i2.initialize( 20, 0, 130, Operation::INSERT, 2);
r1.initialize( 10, 0, 140, Operation::REMOVE, 1);
i2.initialize( 20, 0, 130, Operation::INSERT, 2);
r4.initialize( 92, 0, 94, Operation::REMOVE, 4);
r5.initialize( 96, 0, 98, Operation::REMOVE, 5);
n1.initialize( 30, 0, 100, Operation::REMOVE, -1);
i3.initialize( 40, 0, 50, Operation::INSERT, 3);
i1.initialize( 60, 0, 70, Operation::INSERT, 1);
r2.initialize( 80, 0, 90, Operation::REMOVE, 2);
r3.initialize(110, 0, 120, Operation::REMOVE, 3);
Order** linearization;
linearization = linearize_by_min_max(ops, num_ops);
// for (int i = 0; i < num_ops; i++) {
// assert(linearization[i] != NULL);
// print_op(linearization[i]->operation);
// }
assert (linearization[0]->operation == &i4);
assert (linearization[1]->operation == &i5);
assert (linearization[2]->operation == &n1);
assert (linearization[3]->operation == &i2);
assert (linearization[4]->operation == &i3);
assert (linearization[5]->operation == &i1);
assert (linearization[6]->operation == &r2);
assert (linearization[7]->operation == &r4);
assert (linearization[8]->operation == &r5);
assert (linearization[9]->operation == &r3);
assert (linearization[10]->operation == &r1);
printf("%s passed!\n", __func__);
}
/// This test tests the selectable function for null-returns
void test_null_return4() {
Operation i1, i2, i3, r1, r2, r3, n1;
const int num_ops = 7;
Operation* ops[num_ops] = {
&i1
, &r1
, &n1
, &i2
, &r2
, &i3
, &r3
};
i1.initialize( 1, 0, 2, Operation::INSERT, 1);
i2.initialize( 3, 0, 5, Operation::INSERT, 2);
n1.initialize( 4, 0, 14, Operation::REMOVE, -1);
i3.initialize( 6, 0, 7, Operation::INSERT, 3);
r3.initialize( 8, 0, 9, Operation::REMOVE, 3);
r1.initialize(10, 0, 11, Operation::REMOVE, 1);
r2.initialize(12, 0, 13, Operation::REMOVE, 2);
Order** linearization;
linearization = linearize_by_min_sum(ops, num_ops, linearize_by_invocation(ops, num_ops));
assert (linearization[0]->operation == &i1);
assert (linearization[1]->operation == &i2);
assert (linearization[2]->operation == &i3);
assert (linearization[3]->operation == &r3);
assert (linearization[4]->operation == &r1);
assert (linearization[5]->operation == &r2);
assert (linearization[6]->operation == &n1);
printf("%s passed!\n", __func__);
}
// This test checks if the selectable function for insert operations considers
// null-returns.
void test_null_return5() {
Operation i1, i2, r1, r2, n1, n2;
const int num_ops = 6;
Operation* ops[num_ops] = {
&i1
, &r1
, &n1
, &n2
, &i2
, &r2
};
i1.initialize( 1, 0, 3, Operation::INSERT, 1);
i2.initialize( 2, 0, 8, Operation::INSERT, 2);
n1.initialize( 4, 0, 5, Operation::REMOVE, -1);
n2.initialize( 6, 0, 7, Operation::REMOVE, -1);
r2.initialize( 9, 0, 10, Operation::REMOVE, 2);
r1.initialize(11, 0, 12, Operation::REMOVE, 1);
Order** linearization;
linearization = linearize_by_min_sum(ops, num_ops, linearize_by_invocation(ops, num_ops));
assert (linearization[0]->operation == &i1);
assert (linearization[1]->operation == &n1);
assert (linearization[2]->operation == &n2);
assert (linearization[3]->operation == &i2);
assert (linearization[4]->operation == &r2);
assert (linearization[5]->operation == &r1);
printf("%s passed!\n", __func__);
}
void test_null_return6() {
Operation i1, i2, r1, r2, n1;
const int num_ops = 5;
Operation* ops[num_ops] = {
&i1
, &r1
, &n1
, &i2
, &r2
};
i1.initialize( 1, 0, 9, Operation::INSERT, 1);
r2.initialize( 2, 0, 8, Operation::REMOVE, 2);
i2.initialize( 3, 0, 4, Operation::INSERT, 2);
n1.initialize( 5, 0, 7, Operation::REMOVE, -1);
r1.initialize( 6, 0, 10, Operation::REMOVE, 1);
Order** linearization;
linearization = linearize_by_min_max(ops, num_ops);
// for (int i = 0; i < num_ops; i++) {
// assert(linearization[i] != NULL);
// print_op(linearization[i]->operation);
// }
assert (linearization[0]->operation == &i2);
assert (linearization[1]->operation == &r2);
assert (linearization[2]->operation == &n1);
assert (linearization[3]->operation == &i1);
assert (linearization[4]->operation == &r1);
printf("%s passed!\n", __func__);
}
void test_prophetic_dequeue() {
Operation i1, i2, r1, r2;
const int num_ops = 4;
Operation* ops[num_ops] = {
&i1
, &r1
, &i2
, &r2
};
i1.initialize( 1, 0, 8, Operation::INSERT, 1);
r1.initialize( 2, 0, 4, Operation::REMOVE, 1);
r2.initialize( 3, 0, 6, Operation::REMOVE, 2);
i2.initialize( 5, 0, 7, Operation::INSERT, 2);
Order** linearization;
linearization = linearize_by_min_max(ops, num_ops);
assert (linearization[0]->operation == &i1);
assert (linearization[1]->operation == &r1);
assert (linearization[2]->operation == &i2);
assert (linearization[3]->operation == &r2);
printf("%s passed!\n", __func__);
}
/// This test tests the selectable function for null-returns
void test_convergence() {
int num_ops = 46;
Operation** ops = parse_logfile("test_convergence.lin", num_ops);
Order** linearization;
linearization = linearize_by_min_sum(ops, num_ops, linearize_by_invocation(ops, num_ops));
Element** elements = convert_order_to_elements(linearization, num_ops);
Result* result = calculate_age(elements, num_ops);
printf("max: %"PRIu64"; num_ops: %"PRIu64"; total: %"PRIu64"; average: %0.3f\n",
result->max_costs, result->num_ops, result->total_costs, result->avg_costs);
// for (int i = 0; i < num_ops; i++) {
// assert(linearization[i] != NULL);
// print_op(linearization[i]->operation);
// }
assert(result->total_costs == 156);
printf("%s passed!\n", __func__);
}
int main(int argc, char** argv) {
test_convergence();
test_selectable_insert();
test_selectable_remove();
test_equal_time_stamp_max();
test_equal_time_stamp_sum();
test_null_return1();
test_null_return2();
test_null_return3();
test_null_return4();
test_null_return5();
test_null_return6();
test_max_dev_null_return();
test_prophetic_dequeue();
}
|
55da647a4ff3824c0e19d988c5b5994a31b262fa
|
e3b3544802ae6558e221e43b27d7e62d85f539f1
|
/coms_manager/src/ipmanager.cpp
|
6fcf9caa9cf3e4cd2cb0a12beded6dbcec90ff97
|
[] |
no_license
|
thshorrock/laboratory-hardware
|
fa71463e3a4dcd026f19beff02d2aa2434f09e9c
|
077cac877502f9c475eb5905d957e37b541d6431
|
refs/heads/master
| 2021-01-19T00:16:59.101777
| 2011-10-17T12:01:50
| 2011-10-17T12:01:50
| 2,591,461
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 12,217
|
cpp
|
ipmanager.cpp
|
#include "coms_manager/ipmanager.hpp"
#include <boost/bind.hpp>
#include <boost/lambda/bind.hpp>
#include <boost/array.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>
#include <boost/thread.hpp>
void
ICR::coms::IPmanager::open()
{
m_error = boost::asio::error::host_not_found;
bool connection_failed = true;
size_t count = 0;
while (connection_failed){
boost::asio::ip::tcp::resolver resolver(m_io_service);
boost::asio::ip::tcp::resolver::query query(m_address, m_port);
boost::asio::ip::tcp::resolver::iterator iter = resolver.resolve(query);
boost::asio::ip::tcp::resolver::iterator end; // End marker.
while (m_error && iter != end)
{
m_socket.close();
m_socket.connect(*iter++, m_error);
}
if (m_error){ //still
if ( m_error == boost::asio::error::connection_refused) {
std::cout<<"open connection refused, please sort out the problem (try to reconnect to the network) and press any key followed by enter..."<<std::endl;
char c;
std::cin>> c;
}
else if (m_error == boost::asio::error::host_unreachable)
{
std::cout<<"host unreachable, please check your wires, ping the devices, reconnect to the network, make sure everything is okay and press any key followed by enter..."<<std::endl;
char c;
std::cin>> c;
}
//try to recue
//sleep(200);//go to sleep
++count;
}
else
connection_failed = false;
if (count>10) //could not rescue
{
if ( m_error == boost::asio::error::connection_refused) {
std::cout<<"open connection refused, please sort out the problem (try to reconnect to the network) and press any key followed by enter..."<<std::endl;
char c;
std::cin>> c;
}
else if (m_error == boost::asio::error::host_unreachable)
{
std::cout<<"host unreachable, please check your wires, ping the devices, reconnect to the network, make sure everything is okay and press any key followed by enter..."<<std::endl;
char c;
std::cin>> c;
}
else if ( m_error == boost::asio::error::connection_aborted) {
std::cout<<"open connection aborted, retrying"<<std::endl;
}
else if (m_error == boost::asio::error::connection_reset)
{
std::cout<<"connection reset by peer error in open"<<std::endl;
}
else if (m_error == boost::asio::error::broken_pipe) {
std::cout<<"broken pipe in open, trying to fix..."<<std::endl;
}
else if (m_error == boost::asio::error::timed_out)
{
std::cout<<"connection timed out , trying again"<<std::endl;
}
else{
std::cout<<"open erroc_code value = "<<m_error.value()<<std::endl;
}
std::cout<<"Something is wrong - I cannot open the IP address. Please inspect the error messages and try to fix. I am going to sleep for 1 minute"<<std::endl;
boost::this_thread::sleep(boost::posix_time::seconds(60));
}
}
}
ICR::coms::IPmanager::IPmanager(const std::string& address, const std::string& port)
: coms_manager(),
m_io_service(),
m_socket(m_io_service),
m_error(boost::asio::error::host_not_found),
m_address(address), m_port(port)
{
open();
}
ICR::coms::IPmanager::~IPmanager(){m_socket.close();}
void
ICR::coms::IPmanager::no_delay(const bool& do_not_delay)
{
boost::asio::ip::tcp::no_delay no_delay_option(do_not_delay);
m_socket.set_option(no_delay_option);
}
void
ICR::coms::IPmanager::keep_alive(const bool& do_keep_alive)
{
boost::asio::socket_base::keep_alive keep_alive_option(do_keep_alive);
m_socket.set_option(keep_alive_option);
}
void
ICR::coms::IPmanager::send(const std::string& cmd)
{
bool sent = false;
size_t count = 0;
while (!sent)
{
if (!m_error) //should get reset with the open
boost::asio::write(m_socket,
boost::asio::buffer(cmd),
boost::asio::transfer_all(),
m_error
);
if (m_error)
{
//try to rescue
cancel();
close();
open();//reopen socket - should reset m_error if successful
}
else
sent = true;
// boost::this_thread::sleep(boost::posix_time::milliseconds(100));
if (count>10) //could not rescue
{
std::cout<<"send erroc_code value = "<<m_error.value()<<std::endl;
if ( m_error == boost::asio::error::connection_aborted) {
std::cout<<"send connection aborted, retrying"<<std::endl;
}
else if ( m_error == boost::asio::error::broken_pipe) {
std::cout<<"broken pipe in send, trying to fix..."<<std::endl;
}
std::string cmd_beg;
if (cmd.size()<100)
for(size_t i=0;i<cmd.size();++i){
cmd_beg.push_back(cmd[i]);
}
else
for(size_t i=0;i<100;++i){
cmd_beg.push_back(cmd[i]);
}
std::cout<<"Something is wrong - I cannot send the command '"
<<cmd_beg
<<"' over the IP address. Please inspect the error messages and try to fix. I am going to sleep for 1 minute"<<std::endl;
boost::this_thread::sleep(boost::posix_time::seconds(60));
}
}
}
std::string
ICR::coms::IPmanager::recv( const unsigned long& buffsize, const bool& size_exactly )
throw(exception::exception_in_receive_you_must_resend_command )
{
char * buf = (char*) malloc(buffsize);
size_t len;
if (size_exactly){
len = buffsize;
boost::asio::read(m_socket,
boost::asio::buffer(buf, buffsize)
,
boost::asio::transfer_all(),
m_error
);
}
else
len =m_socket.read_some(boost::asio::buffer(buf, buffsize), m_error);
std::string ret(buf,len ); //Note need this construction to make it a char array and NOT a c-string
// for(size_t i=0;i<len;++i){
// ret.push_back(buf[i]);
// }
//When the server closes the connection, the ip::tcp::socket::read_some() function will exit with the boost::asio::error::eof m_error, which is how we know to exit the loop.
if (m_error) { //some kind of exception
free(buf); //cleanup
if ( m_error == boost::asio::error::connection_aborted) {
std::cout<<"recv connection aborted, retrying"<<std::endl;
}
else if (m_error == boost::asio::error::connection_reset)
{
std::cout<<"connection reset error in recv"<<std::endl;
}
else if (m_error == boost::asio::error::broken_pipe) {
std::cout<<"broken pipe in recv, trying to fix..."<<std::endl;
}
else
std::cout<<"recv error :: erroc_code value = "<<m_error.value()<<std::endl;
//try to recue
cancel();
close();
open();//reopen socket
// //receive_some to cleanup spillage (excess characters this have not been sent).
// std::cout<<"problem in recv - about to try to cleanup "<<std::endl;
// try{
// timed_recv(buffsize,1, false); //retry
// } catch (...) {}
// std::cout<<" ... cleanup complete\n \n ****** you must now resend the command ******* "<<std::endl;
throw exception::exception_in_receive_you_must_resend_command();
}
else //no error
free(buf); //cleanup
return ret;
}
std::string
ICR::coms::IPmanager::timed_recv(const unsigned long& buffsize, const double& seconds, const bool& size_exactly )
throw(exception::timeout_exceeded,
exception::exception_in_receive_you_must_resend_command
)
{
char * buf = (char*) malloc(buffsize);
boost::asio::deadline_timer timer(m_socket.io_service());
boost::optional<boost::system::error_code> timer_result;
timer.expires_from_now(boost::posix_time::seconds(seconds));
timer.async_wait(boost::bind(&check_timeout, &timer_result, _1));
boost::optional<boost::system::error_code> read_result;
unsigned int actually_read = 0;
if (size_exactly){
// std::cout<<"exactly"<<std::endl;
boost::asio::async_read(m_socket, boost::asio::buffer(buf, buffsize),
boost::asio::transfer_all(),
boost::bind(&check_timeout_and_size, &read_result, _1,&actually_read,_2));
}
else
m_socket.async_read_some(boost::asio::buffer(buf, buffsize),
boost::bind(&check_timeout_and_size, &read_result, _1,&actually_read,_2) );
m_socket.io_service().reset();
bool times_up = false;
while (m_socket.io_service().run_one())
{
if (read_result) {
timer.cancel();
}
else if (timer_result)
{
m_socket.cancel();
//std::cout<<"timer has exceeded from ip manager"<<std::endl;
times_up = true;
}
}
if (times_up)
{
free(buf);
throw exception::timeout_exceeded();
}
if (*read_result)
{
free(buf);
//some sort of exception.
if ( *read_result == boost::asio::error::connection_aborted) {
std::cout<<" ip timed_recv connection aborted, retrying"<<std::endl;
}
else if (*read_result == boost::asio::error::connection_reset)
{
std::cout<<"connection reset error in ip timed_recv"<<std::endl;
}
else if (*read_result == boost::asio::error::broken_pipe) {
std::cout<<"broken pipe in ip timed_recv, trying to fix..."<<std::endl;
}
else if (*read_result == boost::asio::error::operation_aborted) {
std::cout<<"operation aborted, retrying"<<std::endl;
}
else if (*read_result == boost::asio::error::bad_descriptor) {
std::cout<<"bad file descriptor, retrying"<<std::endl;
}
else {
std::cout<<"timed_recv ip erroc_code value = "<<*read_result<<std::endl;
//throw boost::system::system_error(*read_result);
}
//try to recue
cancel();
close();
open();//reopen socket
std::cout<<"reopened"<<std::endl;
//std::cout<<"problem in timed_recv - cleaning up ... "<<std::endl;
//resend
// try{
// timed_recv(buffsize,seconds, false); //retry
// } catch (...) {}
// std::cout<<" ... cleanup complete\n \n ****** you must now resend the command ******* "<<std::endl;
throw exception::exception_in_receive_you_must_resend_command();
}
std::string ret(buf,actually_read ); //Note need this construction to make it a char array and NOT a c-string
// std::string ret;
// for(size_t i=0;i<actually_read;++i){
// ret.push_back(buf[i]);
// }
free(buf); //cleanup
//ret.append(buf);
return ret;
}
// free(buf);
// std::cout<<"read result = "<<read_result<<std::endl;
// if (!m_socket.is_open()) {
// std::cout<<"socket closed trying to reopen"<<std::endl;
// open();
// }
// else{
// std::cout<<"socket open, will try to reopen"<<std::endl;
// cancel();
// close();
// open();
// }
///if (*read_result == boost::asio::error::operation_aborted )
// throw exception::timeout_exceeded();
// else if (
// (*read_result == boost::asio::error::connection_reset)
// ||
// (*read_result == boost::asio::error::connection_refused)
// ) {
// std::cout<<"connection reset error in timed_recv"<<std::endl;
// cancel();
// close();
// //may need to reset the io_serice here
// open();
// timed_recv(buffsize,seconds, size_exactly);
// }
// else
// {
// std::cout<<"timed recv error"<<std::endl;
// throw boost::system::system_error(*read_result);
// }
std::string
ICR::coms::IPmanager::recv(const std::string& cmd, const unsigned long& buffsize, const bool& size_exactly )
throw( )
{
//send quiery and await repsonse
for(;;){
try
{
IPmanager::send(cmd);
return recv(buffsize,size_exactly);
}
catch(exception::exception_in_receive_you_must_resend_command& e)
{
std::cout<<"exception in recv caught - resending the command"<<std::endl;
}
}
}
std::string
ICR::coms::IPmanager::timed_recv(const std::string& cmd, const unsigned long& buffsize, const double& seconds, const bool& size_exactly )
throw(exception::timeout_exceeded )
{
//send quiery and await repsonse
for(;;){
try
{
IPmanager::send(cmd);
return timed_recv(buffsize,seconds,size_exactly);
}
catch(exception::exception_in_receive_you_must_resend_command& e)
{
std::cout<<"exception in timed_recv caught - resending the command"<<std::endl;
}
}
}
|
5e07e846b178da9cbd0c006d4db4f64464185bbd
|
2c2390232d175cecbcafeedae39bc2943ddf8452
|
/UIShop/IUIMFCToolBar.cpp
|
6c5d63d360be99c00f1aada83edb3b5a555b75e0
|
[] |
permissive
|
iUIShop/LibUIDK
|
d36621fbf3551b1c8ac5b6a44a2df1769a73a4f6
|
ea7b0ca3ba1e58867bb35fdaa32b8685a3f83409
|
refs/heads/master
| 2023-04-13T04:37:35.618021
| 2023-03-30T09:53:55
| 2023-03-30T09:53:55
| 207,088,755
| 418
| 204
|
MIT
| 2019-09-09T13:52:26
| 2019-09-08T09:19:02
|
C++
|
UTF-8
|
C++
| false
| false
| 4,782
|
cpp
|
IUIMFCToolBar.cpp
|
// IUIMFCToolBar.cpp : implementation file
//
#include "stdafx.h"
#include "UIShop.h"
#include "IUIMFCToolBar.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
// CIUIMFCToolBar
IMPLEMENT_DYNAMIC(CIUIMFCToolBar, CMFCToolBar)
CIUIMFCToolBar::CIUIMFCToolBar()
{
}
CIUIMFCToolBar::~CIUIMFCToolBar()
{
}
BEGIN_MESSAGE_MAP(CIUIMFCToolBar, CMFCToolBar)
END_MESSAGE_MAP()
// CIUIMFCToolBar message handlers
BOOL CIUIMFCToolBar::LoadBitmapEx(CMFCToolBarInfo& params, BOOL bLocked)
{
m_bLocked = bLocked;
if (m_bLocked)
{
// Don't add bitmap to the shared resources!
if (!m_ImagesLocked.Load(params.m_uiHotResID, NULL, TRUE))
{
return FALSE;
}
if (params.m_uiColdResID != 0)
{
if (!m_ColdImagesLocked.Load(params.m_uiColdResID, NULL, TRUE))
{
return FALSE;
}
ASSERT(m_ImagesLocked.GetCount() == m_ColdImagesLocked.GetCount());
}
else if (m_bAutoGrayInactiveImages)
{
m_ImagesLocked.CopyTo(m_ColdImagesLocked);
m_ColdImagesLocked.GrayImages(m_nGrayImagePercentage);
}
if (params.m_uiDisabledResID != 0)
{
if (!m_DisabledImagesLocked.Load(params.m_uiDisabledResID, NULL, TRUE))
{
return FALSE;
}
ASSERT(m_ImagesLocked.GetCount() == m_DisabledImagesLocked.GetCount());
}
// Load large images:
if (params.m_uiLargeHotResID != 0)
{
if (!m_LargeImagesLocked.Load(params.m_uiLargeHotResID, NULL, TRUE))
{
return FALSE;
}
ASSERT(m_ImagesLocked.GetCount() == m_LargeImagesLocked.GetCount());
}
if (params.m_uiLargeColdResID != 0)
{
ASSERT(params.m_uiColdResID != 0);
if (!m_LargeColdImagesLocked.Load(params.m_uiLargeColdResID, NULL, TRUE))
{
return FALSE;
}
ASSERT(m_ImagesLocked.GetCount() == m_LargeColdImagesLocked.GetCount());
}
if (params.m_uiLargeDisabledResID != 0)
{
ASSERT(params.m_uiDisabledResID != 0);
if (!m_LargeDisabledImagesLocked.Load(params.m_uiLargeDisabledResID, NULL, TRUE))
{
return FALSE;
}
ASSERT(m_ImagesLocked.GetCount() == m_LargeDisabledImagesLocked.GetCount());
}
if (params.m_uiMenuResID != 0)
{
if (!m_MenuImagesLocked.Load(params.m_uiMenuResID, NULL, TRUE))
{
return FALSE;
}
ASSERT(m_ImagesLocked.GetCount() == m_MenuImagesLocked.GetCount());
}
if (params.m_uiMenuDisabledResID != 0)
{
if (!m_MenuImagesLocked.Load(params.m_uiMenuResID, NULL, TRUE))
{
return FALSE;
}
ASSERT(m_ImagesLocked.GetCount() == m_MenuImagesLocked.GetCount());
}
return TRUE;
}
if (!m_Images.Load(params.m_uiHotResID, NULL, TRUE))
{
return FALSE;
}
m_iImagesOffset = m_Images.GetResourceOffset(params.m_uiHotResID);
ASSERT(m_iImagesOffset >= 0);
if (params.m_uiColdResID != 0)
{
if (!m_ColdImages.Load(params.m_uiColdResID, NULL, TRUE))
{
return FALSE;
}
ASSERT(m_Images.GetCount() == m_ColdImages.GetCount());
ASSERT(m_Images.GetImageSize().cy == m_ColdImages.GetImageSize().cy);
}
else if (m_bAutoGrayInactiveImages)
{
m_Images.CopyTo(m_ColdImages);
m_ColdImages.GrayImages(m_nGrayImagePercentage);
}
if (params.m_uiMenuResID != 0)
{
if (!m_MenuImages.Load(params.m_uiMenuResID, NULL, TRUE))
{
return FALSE;
}
ASSERT(m_Images.GetCount() == m_MenuImages.GetCount());
ASSERT(m_MenuImages.GetImageSize().cy == m_sizeMenuImage.cy);
}
if (params.m_uiDisabledResID != 0)
{
if (!m_DisabledImages.Load(params.m_uiDisabledResID, NULL, TRUE))
{
return FALSE;
}
ASSERT(m_Images.GetCount() == m_DisabledImages.GetCount());
}
if (params.m_uiMenuDisabledResID != 0)
{
if (!m_DisabledMenuImages.Load(params.m_uiMenuDisabledResID, NULL, TRUE))
{
return FALSE;
}
ASSERT(m_Images.GetCount() == m_DisabledMenuImages.GetCount());
}
ASSERT(m_Images.GetImageSize().cy == m_sizeImage.cy);
// Load large images:
if (params.m_uiLargeHotResID != 0)
{
if (!m_LargeImages.Load(params.m_uiLargeHotResID, NULL, TRUE))
{
return FALSE;
}
ASSERT(m_Images.GetCount() == m_LargeImages.GetCount());
}
if (params.m_uiLargeColdResID != 0)
{
ASSERT(params.m_uiColdResID != 0);
if (!m_LargeColdImages.Load(params.m_uiLargeColdResID, NULL, TRUE))
{
return FALSE;
}
ASSERT(m_Images.GetCount() == m_LargeColdImages.GetCount());
}
if (params.m_uiLargeDisabledResID != 0)
{
ASSERT(params.m_uiDisabledResID != 0);
if (!m_LargeDisabledImages.Load(params.m_uiLargeDisabledResID, NULL, TRUE))
{
return FALSE;
}
ASSERT(m_Images.GetCount() == m_LargeDisabledImages.GetCount());
}
return TRUE;
}
|
5fcfe51cf32a98c8ce587152628765bfb8fcdf83
|
e428d1c90f7ce6a5b2420668863c5efe064c8662
|
/Starfarm/src/System/RendererSystem.cpp
|
de5600be2c6d8196238e97e96af92cfe3f036f4a
|
[
"MIT"
] |
permissive
|
TiphaineLAURENT/Starfarm
|
5306ad0236ea30b9780aae12eacc3c262ae9352f
|
08d7fa75a36a465aa33c10eadcc9c2ef6f4548f5
|
refs/heads/master
| 2020-05-05T08:12:44.435533
| 2019-08-05T13:57:38
| 2019-08-05T13:57:38
| 179,854,186
| 1
| 2
|
MIT
| 2019-08-05T13:52:26
| 2019-04-06T15:55:58
|
C++
|
UTF-8
|
C++
| false
| false
| 934
|
cpp
|
RendererSystem.cpp
|
//
// Created by tiphaine on 11/04/19.
//
#include <iostream>
#include <ComponentManager.hpp>
#include "RendererSystem.hpp"
#include "../Component/SpriteComponent.hpp"
#include "../Component/TextComponent.hpp"
namespace game
{
RendererSystem::RendererSystem(sf::RenderWindow *const window)
: System(), _window(window)
{
}
void RendererSystem::preUpdate()
{
_window->display();
}
void RendererSystem::update()
{
_window->clear();
}
void RendererSystem::postUpdate()
{
for (auto &component :
ecs::ComponentManager::getComponentContainer<SpriteComponent>
()) {
_window->draw(*component);
}
for (auto &component :
ecs::ComponentManager::getComponentContainer<TextComponent>
()) {
_window->draw(*component);
}
}
}
|
5b2d6c741195d8e9a03ed92bf68e6af195f5e31e
|
f251f8ed67493aaf89fad9535b29adf0d2f995a1
|
/soj_2119.cpp
|
20f304d40ab36699286baf71ae8404673e01aa8f
|
[] |
no_license
|
443singer/soj
|
4fe391c908e9f0b90201bb7367245753a90ec8a5
|
d98ed24d5d0796cc85b2979bae82bd0728f529f2
|
refs/heads/master
| 2021-08-30T19:42:04.328587
| 2017-12-19T07:13:32
| 2017-12-19T07:13:32
| 114,731,725
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 842
|
cpp
|
soj_2119.cpp
|
#include <cstdio>
#include <iostream>
#include <cstring>
#include <algorithm>
#include <cmath>
using namespace std;
int n;
int a[10][10];
int b[10];
int ans = 1e7;
void dfs(int dep) {
if(dep>n) {
int tmp = -1e7;
for(int j = 0 ; j < n ; ++j) {
int tmp2 = 0;
for(int i = 0 ; i < n ; ++i) {
tmp2 += a[i][(j+b[i])%n];
}
tmp = max(tmp2,tmp);
}
ans = min(ans,tmp);
return;
}
for(int i = 0 ; i < n ; ++i) {
b[dep-1] = i;
dfs(dep+1);
}
}
int main() {
while(scanf("%d",&n),n!=-1) {
ans = 1e7;
for(int i = 0 ; i < n ; ++i)
for(int j = 0 ; j < n ; ++j)
scanf("%d",&a[i][j]);
dfs(2);
printf("%d\n",ans);
}
}
|
a53d505cdcb1710ad89b4fb53104c87f2d9447b2
|
eb509cc64c2af406a0a372f4515a56844718f5ce
|
/src/UnidadesMovibles/devastador.h
|
e2481b6ba089702faccc58bb122a53f85e325275
|
[] |
no_license
|
ramoro/Dune
|
85877e495204233eb445a22c91bd81603de266b3
|
17762e0327bc4d09c86ec43b72bf691a99ca4b87
|
refs/heads/master
| 2020-04-01T11:28:16.615954
| 2018-12-04T20:19:10
| 2018-12-04T20:19:10
| 153,163,721
| 0
| 2
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,013
|
h
|
devastador.h
|
#ifndef DEVASTADOR_H
#define DEVASTADOR_H
#include "vehiculo.h"
#include <utility>
#include <vector>
/*Clase que representa una unidad de un devastador en el mundo de Dune.
Es un tanque altamente blindado que al ser destruido explota daniando
todo aquel que este cerca.*/
class Devastador: public Vehiculo {
private:
int danio_explosion;
std::vector<int> config_explosion;
public:
/*Constructor de la clase.*/
Devastador(int id, int id_duenio, std::pair<int, int> centro,
Config &config);
/*Recibe el mapa y el id del objeto y devuelve todas las unidades
afectadas por su ataque.*/
virtual std::vector<ObjetoDune*> atacar_objetivo(Mapa &mapa,
int id_objetivo);
/*Mata a la unidad seteandola como muerta. Le equipa el arma
de explosion para daniar con su explosion al morir.*/
virtual void matar();
/*En caso de tener un ataque al morir lo ejecuta y devuelve
un vector con los objetos afectados.*/
virtual std::vector<ObjetoDune*> ataque_al_morir(Mapa &mapa);
};
#endif
|
d4815737ac6eb5b511e6795aa4ec0b0210d85429
|
335099e4850cb84edb059c671ced5ded847c7e10
|
/source/save/savehint.cpp
|
e7bc322f64af65515155c3a4ceae6dbef583a0fb
|
[
"Zlib"
] |
permissive
|
dmdware/sfh
|
a260bf771d0017a397f54219f37fb1ea7eb86e87
|
b7b0bf71634b864645e04effd8c745696c454d7c
|
refs/heads/master
| 2021-01-17T10:40:27.407838
| 2016-12-10T03:25:20
| 2016-12-10T03:25:20
| 38,033,367
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 940
|
cpp
|
savehint.cpp
|
#include "savehint.h"
#include "../trigger/hint.h"
void SaveHint(Hint* h, FILE* fp)
{
int32_t len = strlen(h->message.c_str())+1;
fwrite(&len, sizeof(int32_t), 1, fp);
fwrite(h->message.c_str(), sizeof(char), len, fp);
len = strlen(h->graphic.c_str())+1;
fwrite(&len, sizeof(int32_t), 1, fp);
fwrite(h->graphic.c_str(), sizeof(char), len, fp);
fwrite(&h->gwidth, sizeof(int32_t), 1, fp);
fwrite(&h->gheight, sizeof(int32_t), 1, fp);
}
void ReadHint(Hint* h, FILE* fp)
{
int32_t len;
fread(&len, sizeof(int32_t), 1, fp);
char* buff = new char[len];
fread(buff, sizeof(char), len, fp);
h->message = buff;
delete [] buff;
fread(&len, sizeof(int32_t), 1, fp);
buff = new char[len];
fread(buff, sizeof(char), len, fp);
h->graphic = buff;
delete [] buff;
fread(&h->gwidth, sizeof(int32_t), 1, fp);
fread(&h->gheight, sizeof(int32_t), 1, fp);
}
void SaveLastHint(FILE* fp)
{
}
void ReadLastHint(FILE* fp)
{
}
|
a4eef533c4429b69ab8be097157df9b854c1401d
|
2d361696ad060b82065ee116685aa4bb93d0b701
|
/src/algo/blast/proteinkmer/pearson.hpp
|
5e00d2fc7c00faf47a2315174370a69f0ccb5e26
|
[
"LicenseRef-scancode-public-domain"
] |
permissive
|
AaronNGray/GenomeWorkbench
|
5151714257ce73bdfb57aec47ea3c02f941602e0
|
7156b83ec589e0de8f7b0a85699d2a657f3e1c47
|
refs/heads/master
| 2022-11-16T12:45:40.377330
| 2020-07-10T00:54:19
| 2020-07-10T00:54:19
| 278,501,064
| 1
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 3,414
|
hpp
|
pearson.hpp
|
/* $Id: pearson.hpp
* ===========================================================================
*
* PUBLIC DOMAIN NOTICE
* National Center for Biotechnology Information
*
* This software/database is a "United States Government Work" under the
* terms of the United States Copyright Act. It was written as part of
* the author's official duties as a United States Government employee and
* thus cannot be copyrighted. This software/database is freely available
* to the public for use. The National Library of Medicine and the U.S.
* Government have not placed any restriction on its use or reproduction.
*
* Although all reasonable efforts have been taken to ensure the accuracy
* and reliability of the software and data, the NLM and the U.S.
* Government do not and cannot warrant the performance or results that
* may be obtained by using this software or data. The NLM and the U.S.
* Government disclaim all warranties, express or implied, including
* warranties of performance, merchantability or fitness for any particular
* purpose.
*
* Please cite the author in any work or product based on this material.
*
* ===========================================================================
*
* Author: Tom Madden
*
* File Description:
* Calculate Pearson hash per:
* http://portal.acm.org/citation.cfm?id=78978
* http://cs.mwsu.edu/~griffin/courses/2133/downloads/Spring11/p677-pearson.pdf
*
*
*/
#include <corelib/ncbistd.hpp>
/* copied from wikipedia. produce my own? */
const unsigned char pearson_tab[256] = {
// 256 values 0-255 in any (random) order suffices
98, 6, 85,150, 36, 23,112,164,135,207,169, 5, 26, 64,165,219, // 1
61, 20, 68, 89,130, 63, 52,102, 24,229,132,245, 80,216,195,115, // 2
90,168,156,203,177,120, 2,190,188, 7,100,185,174,243,162, 10, // 3
237, 18,253,225, 8,208,172,244,255,126,101, 79,145,235,228,121, // 4
123,251, 67,250,161, 0,107, 97,241,111,181, 82,249, 33, 69, 55, // 5
59,153, 29, 9,213,167, 84, 93, 30, 46, 94, 75,151,114, 73,222, // 6
197, 96,210, 45, 16,227,248,202, 51,152,252,125, 81,206,215,186, // 7
39,158,178,187,131,136, 1, 49, 50, 17,141, 91, 47,129, 60, 99, // 8
154, 35, 86,171,105, 34, 38,200,147, 58, 77,118,173,246, 76,254, // 9
133,232,196,144,198,124, 53, 4,108, 74,223,234,134,230,157,139, // 10
189,205,199,128,176, 19,211,236,127,192,231, 70,233, 88,146, 44, // 11
183,201, 22, 83, 13,214,116,109,159, 32, 95,226,140,220, 57, 12, // 12
221, 31,209,182,143, 92,149,184,148, 62,113, 65, 37, 27,106,166, // 13
3, 14,204, 72, 21, 41, 56, 66, 28,193, 40,217, 25, 54,179,117, // 14
238, 87,240,155,180,170,242,212,191,163, 78,218,137,194,175,110, // 15
43,119,224, 71,122,142, 42,160,104, 48,247,103, 15, 11,138,239 // 16
};
// Pearson hash takes a string of bytes and returns one byte key.
unsigned char pearson_hash(unsigned char* key, int length, int init);
// Do three pearson hashes in a row on the key.
uint32_t do_pearson_hash(unsigned char *key, int length);
/// Do two pearson hashes in a row on the key.
uint32_t do_pearson_hash2bytes(unsigned char *key, int length);
/// Pearson hash an integer into one byte.
unsigned char pearson_hash_int2byte(uint32_t input, int seed1=11);
/// Pearson hash an integer into two bytes.
uint16_t pearson_hash_int2short(uint32_t input, int seed1=11, int seed2=101);
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.