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
|
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
9990257a95cb12afa5762b22a0080a4be9400b2d
|
ec8f6238a89045c4420b19fe662abc8754a33ead
|
/other/offlinetest/20180921/tree.cpp
|
1a2a0472bf081c504c098bc3e16a05c4f8e76a5e
|
[] |
no_license
|
hajbw/OICodeStorage
|
9fe4748a13ec799aed8c21f67c576f8cfd47d3c6
|
c4c1bbee4c2e0d5c5af792ce6cfb42a7ef5294b0
|
refs/heads/master
| 2021-07-23T22:51:23.816998
| 2018-11-09T13:58:34
| 2018-11-09T13:58:34
| 113,634,410
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 651
|
cpp
|
tree.cpp
|
/*
SweepCup2018 Day2
#3 校门内的树
*/
#include <iostream>
using std::cin;
using std::cout;
const int MAXN = 100010,P = 998244353;
int h[MAXN];
template<class T>T gcd(const T &a,const T &b)
{
return b ? gcd(b,a % b) : a;
}
long long query(const long long &u,const long long &v)
{
long long ans = 1;
for(int i = u;i < v;++i)
{
for(int j = i + 1;j <= v;++j)
{
ans *= gcd(h[i],h[j]);
ans %= P;
}
}
return ans;
}
int main()
{
int n,q,u,v;
cin>>n>>q;
for(int i = 1;i <= n;++i)
cin>>h[i];
for(int i = 0;i < q;++i)
{
cin>>u>>v;
cout<<query(u,v)<<'\n';
}
return 0;
}
|
a4e83e2b4c1e72da00776bcecb02fa3d9fc4a67e
|
e0904d35f0b89fed8ebdeb6e08864c0208006954
|
/MeshLib/Utils/addPropertyToMesh.h
|
3486e0d39e16e9fb14160c5152038ab8af65dcd5
|
[
"BSD-3-Clause",
"BSD-2-Clause"
] |
permissive
|
ufz/ogs
|
e3f7b203ac960eeed81c3ad20e743b2ee2f4753e
|
073d0b9820efa5149578259c0137999a511cfb4f
|
refs/heads/master
| 2023-08-31T07:09:48.929090
| 2023-08-30T09:24:09
| 2023-08-30T09:24:09
| 1,701,384
| 125
| 259
|
BSD-3-Clause
| 2021-04-22T03:28:27
| 2011-05-04T14:09:57
|
C++
|
UTF-8
|
C++
| false
| false
| 2,459
|
h
|
addPropertyToMesh.h
|
/**
* \file
*
* \copyright
* Copyright (c) 2012-2023, OpenGeoSys Community (http://www.opengeosys.org)
* Distributed under a Modified BSD License.
* See accompanying file LICENSE.txt or
* http://www.opengeosys.org/project/license
*
*/
#pragma once
#include <vector>
#include "BaseLib/Error.h"
#include "MeshLib/Location.h"
#include "MeshLib/Mesh.h"
#include "MeshLib/Properties.h"
namespace MeshLib
{
/// Creates a new \c PropertyVector in the given mesh and initializes it with
/// the given data. A \c PropertyVector with the same name must not exist.
/// \param mesh A \c Mesh the new \c ProperyVector will be created in.
/// \param name A string that contains the name of the new \c PropertyVector.
/// \param item_type One of the values \c MeshLib::MeshItemType::Cell or \c
/// \c MeshLib::MeshItemType::Node that shows the association of the property
/// values either to \c Element's / cells or \c Node's
/// \param number_of_components the number of components of a property
/// \param values A vector containing the values that are used for
/// initialization.
template <typename T>
void addPropertyToMesh(Mesh& mesh, std::string_view name,
MeshItemType item_type, std::size_t number_of_components,
std::vector<T> const& values)
{
if (item_type == MeshItemType::Node)
{
if (mesh.getNumberOfNodes() != values.size() / number_of_components)
{
OGS_FATAL(
"Error number of nodes ({:d}) does not match the number of "
"tuples ({:d}).",
mesh.getNumberOfNodes(), values.size() / number_of_components);
}
}
if (item_type == MeshItemType::Cell)
{
if (mesh.getNumberOfElements() != values.size() / number_of_components)
{
OGS_FATAL(
"Error number of elements ({:d}) does not match the number of "
"tuples ({:d}).",
mesh.getNumberOfElements(),
values.size() / number_of_components);
}
}
auto* const property = mesh.getProperties().createNewPropertyVector<T>(
name, item_type, number_of_components);
if (!property)
{
OGS_FATAL("Error while creating PropertyVector '{:s}'.", name);
}
property->reserve(values.size());
std::copy(values.cbegin(), values.cend(), std::back_inserter(*property));
}
} // namespace MeshLib
|
0db9e032368124e78ededed678b01d22c44c2f79
|
68b77031682a6702b5661c1ead4f72004802248b
|
/src/writer.cpp
|
301ad6393b5ed37bcddcd24676a5827e1e962774
|
[] |
no_license
|
naveen-suppala/mpc
|
1c77219f02452b195b8ce2e4645914773ac49c49
|
7006aa4e455344db75d7f2bb462caf3ca02f2329
|
refs/heads/master
| 2021-09-20T18:35:35.175196
| 2018-08-14T06:26:35
| 2018-08-14T06:26:35
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 329
|
cpp
|
writer.cpp
|
#include <iostream>
#include "communicator/Writer.h"
using std::cout;
using std::endl;
int main() {
auto writer=Writer::create("/home/llx/Documents/trading/testjournal","testj5");
for(int i=0;i<=100;++i) {
usleep(10000000);
writer->WriteFrame(static_cast<void *>(&i), sizeof(int));
}
return 0;
}
|
91352d046ad87fd66266552b7aa9236773ac544d
|
0a543beda444f0131c6561c71a4d847c156f5e5d
|
/2_const_function_args.cpp
|
8cc205ed916734472d65d8b6b54d368043e121f7
|
[] |
no_license
|
Mohamed209/CPP_Tutorial
|
208bab0e9425751014192fd85e5ca4099e794708
|
e7a409f756f6ab326226670246e3c62f2b3ac849
|
refs/heads/master
| 2020-08-17T02:50:41.796446
| 2019-10-16T16:44:48
| 2019-10-16T16:44:48
| 215,595,095
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 641
|
cpp
|
2_const_function_args.cpp
|
/*
Suppose you want to pass an argument by reference for efficiency, but not only do you want
the function not to modify it, you want a guarantee that the function cannot modify it.
*/
#include <iostream>
using namespace std;
int sum_two_vars(int& a,int& b);
int sum_two_vars_one_const(int& a,const int& b);
int main()
{
int aar=10;
int bar=20;
cout<<sum_two_vars(aar,bar)<<endl; // ok , should print 30
cout<<sum_two_vars_one_const(aar,bar);
return 0;
}
int sum_two_vars(int& a,int& b)
{
return b=a+b;
}
int sum_two_vars_one_const(int& a,const int& b)
{
return b=a+b; // error cant modify const value
}
|
f2238e72a7366d15e9b1cc06c4b42340ecdf4459
|
e0ddeda75b52fa33938f64af675c090152ca8eca
|
/playground/entity/customOpengl/TransformRect.h
|
bdc8ebfcb003478d07ecadd5c69d801c710d3d8c
|
[] |
no_license
|
HottDog/OpenGLPro
|
b9e6257432f84bc84f4a1200b9e23493eb9d04ed
|
fc6931b5e191d01bdd5eaec39f645c774f31f7c9
|
refs/heads/master
| 2020-04-15T19:52:34.237793
| 2019-07-05T08:39:41
| 2019-07-05T08:39:41
| 164,968,708
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 326
|
h
|
TransformRect.h
|
#pragma once
#include"playground/system/RectTask.h"
class TranformRect :public RectTask {
public:
TranformRect();
protected:
bool virtual Start();
bool virtual Draw();
bool virtual Destroy();
private:
mat4 tranform = mat4(1.0f);
mat4 model;
mat4 view;
mat4 projection;
double speed = 20.0 / HEIGHT;
double h = 0;
};
|
fd9403652594708dca48f41e885c7305d62e0554
|
27787f447b0c9ec037e7b94d3e7c468effe5531c
|
/HISTORY_GAME/SRC_FILES/item.hpp
|
2cae9600c49d466959810eeedbabad0ae938c43d
|
[] |
no_license
|
gougeogl/GLEN-GOUGEON-CODE-PORTFOLIO
|
f8d260fd4271424a84034953e5e5453928467662
|
ba9c2ae5f932281a906913b837f9541c7028ad8b
|
refs/heads/master
| 2022-12-18T18:10:39.559347
| 2020-09-29T00:27:07
| 2020-09-29T00:27:07
| 299,414,414
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,487
|
hpp
|
item.hpp
|
/*****************************************************************************
* File Name: item.hpp
* Programmer: Glen Gougeon
* Last-Mod: 9-4-20
* Game Title: A Nap in Time, A History Major's Unexpected Journey
* Description: Specification for Item Class. Primary structure
for data related to Weapons, Food, Documents etc.
found, lost, or won during gameplay. An 'Item'
performs the 'is a' relationship. Some member vars
only used for printing in game-play.
*****************************************************************************/
#ifndef GOUGEON_ITEM_CLASS_HPP
#define GOUGEON_ITEM_CLASS_HPP
#include<cstdlib>
#include<iostream>
#include<string>
using std::cin;
using std::cout;
using std::string;
enum WOT { WEAPON = 1, HEAVY_WEAPON, BOMB, FOOD, DOCUMENT, THING /* default */ };
class Item
{
private:
string title;
string description;
enum WOT type;
double weight;
double value;
int healthBonus;
int power;
public:
Item();
~Item();
void setTitle(string);
string getTitle() const;
void setDescription(string);
string getDescription() const;
void setType(enum WOT);
enum WOT getType();
void setWeight(double);
double getWeight() const;
void setValue(double);
double getValue() const;
void setHealthBonus(int);
int getHealthBonus() const;
void setPower(int);
int getPower();
void printItem();
};
#endif
// ************************************* EOF ************************************
|
4621ec8f5ff7712b43d6da813053f5040fb7898c
|
f22f1c9b9f0265295be7cb83433fcba66b620776
|
/core/tests/src/main/c++/jcpp/lang/JStringTest.cpp
|
d1540bb9d0c32d60116f5951b0cd1be0f80ef719
|
[] |
no_license
|
egelor/jcpp-1
|
63c72c3257b52b37a952344a62fa43882247ba6e
|
9b5a180b00890d375d2e8a13b74ab5039ac4388c
|
refs/heads/master
| 2021-05-09T03:46:22.585245
| 2015-08-07T16:04:20
| 2015-08-07T16:04:20
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 579
|
cpp
|
JStringTest.cpp
|
#include "jcpp/lang/JStringTest.h"
#include "jcpp/lang/JClass.h"
#include "jcpp/lang/JObject.h"
#include "jcpp/lang/JVoid.h"
#include "jcpp/lang/reflect/JMethod.h"
#include "jcpp/lang/reflect/JConstructor.h"
#include "jcpp/lang/reflect/JModifier.h"
using namespace jcpp::io;
using namespace jcpp::lang;
using namespace jcpp::lang::reflect;
namespace jcpp{
namespace lang{
JStringTest::JStringTest(JString* name):JAbstractTest(getClazz(),name){
}
void JStringTest::testNewString(){
}
JStringTest::~JStringTest(){
}
}
}
|
e5c405a56039b55bd3968a33991d1183f7540c27
|
dd267038685dcefd5f89016c63f72c2ad4aa7fdf
|
/src/ozone/wayland/group/wayland_webos_surface_group.h
|
a2d39de1ab51734944d0b1504340257370fefd66
|
[
"BSD-3-Clause"
] |
permissive
|
webosose/chromium87
|
044d5c74ae9c2815cf096fd98bf9ea4e7e2fe6b3
|
75729b78817d49249cd004ef734c032269f06e53
|
refs/heads/master
| 2022-11-05T07:23:21.710708
| 2021-10-06T11:24:51
| 2021-10-08T08:30:55
| 392,617,373
| 4
| 2
| null | 2022-11-01T02:23:21
| 2021-08-04T08:54:03
| null |
UTF-8
|
C++
| false
| false
| 4,614
|
h
|
wayland_webos_surface_group.h
|
// Copyright 2016-2018 LG Electronics, 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.
//
// SPDX-License-Identifier: Apache-2.0
#ifndef OZONE_WAYLAND_GROUP_WAYLAND_WEBOS_SURFACE_GROUP_H
#define OZONE_WAYLAND_GROUP_WAYLAND_WEBOS_SURFACE_GROUP_H
#include <wayland-webos-surface-group-client-protocol.h>
#include <string>
namespace ozonewayland {
class wl_webos_surface_group_compositor {
public:
wl_webos_surface_group_compositor(struct ::wl_registry* registry, int id);
wl_webos_surface_group_compositor(
struct ::wl_webos_surface_group_compositor* object);
wl_webos_surface_group_compositor();
virtual ~wl_webos_surface_group_compositor();
void init(struct ::wl_registry* registry, int id);
void init(struct ::wl_webos_surface_group_compositor* object);
struct ::wl_webos_surface_group_compositor* object();
const struct ::wl_webos_surface_group_compositor* object() const;
bool isInitialized() const;
struct ::wl_webos_surface_group* create_surface_group(
struct ::wl_surface* parent,
const std::string& name);
struct ::wl_webos_surface_group* get_surface_group(const std::string& name);
private:
struct ::wl_webos_surface_group_compositor*
wl_webos_surface_group_compositor_;
};
class wl_webos_surface_group {
public:
wl_webos_surface_group(struct ::wl_registry* registry, int id);
wl_webos_surface_group(struct ::wl_webos_surface_group* object);
wl_webos_surface_group();
virtual ~wl_webos_surface_group();
void init(struct ::wl_registry* registry, int id);
void init(struct ::wl_webos_surface_group* object);
struct ::wl_webos_surface_group* object();
const struct ::wl_webos_surface_group* object() const;
bool isInitialized() const;
enum z_hint {
z_hint_below = 0, // Below the root surface and the lowest named layer
z_hint_above =
1, // Above the root surface and above the highest named layer
z_hint_top = 2 // Above all of the anonymous surfaces
};
struct ::wl_webos_surface_group_layer* create_layer(const std::string& name,
int32_t z_index);
void attach(struct ::wl_surface* surface, const std::string& layer_name);
void attach_anonymous(struct ::wl_surface* surface, uint32_t z_hint);
void allow_anonymous_layers(uint32_t allow);
void detach(struct ::wl_surface* surface);
void focus_owner();
void focus_layer(const std::string& layer);
void destroy();
protected:
virtual void webos_surface_group_owner_destroyed();
private:
void init_listener();
static const struct wl_webos_surface_group_listener
wl_webos_surface_group_listener_;
static void handle_owner_destroyed(void* data,
struct ::wl_webos_surface_group* object);
struct ::wl_webos_surface_group* wl_webos_surface_group_;
};
class wl_webos_surface_group_layer {
public:
wl_webos_surface_group_layer(struct ::wl_registry* registry, int id);
wl_webos_surface_group_layer(struct ::wl_webos_surface_group_layer* object);
wl_webos_surface_group_layer();
virtual ~wl_webos_surface_group_layer();
void init(struct ::wl_registry* registry, int id);
void init(struct ::wl_webos_surface_group_layer* object);
struct ::wl_webos_surface_group_layer* object();
const struct ::wl_webos_surface_group_layer* object() const;
bool isInitialized() const;
void set_z_index(int32_t z_index);
void destroy();
protected:
virtual void webos_surface_group_layer_surface_attached();
virtual void webos_surface_group_layer_surface_detached();
private:
void init_listener();
static const struct wl_webos_surface_group_layer_listener
wl_webos_surface_group_layer_listener_;
static void handle_surface_attached(
void* data,
struct ::wl_webos_surface_group_layer* object);
static void handle_surface_detached(
void* data,
struct ::wl_webos_surface_group_layer* object);
struct ::wl_webos_surface_group_layer* wl_webos_surface_group_layer_;
};
} // namespace ozonewayland
#endif // OZONE_WAYLAND_GROUP_WAYLAND_WEBOS_SURFACE_GROUP_H
|
0a6d9304f28f236e9a990f5b70abc7182444ddc7
|
95ff1e556221ce299d3247598b3c1d6ac2b9dc67
|
/taekgun.cpp
|
072d9f1b1552f8290ac2964d9147fda6c58331d1
|
[] |
no_license
|
again2002/certi-samples
|
3caa362239217a9a6f8ccaea959bd9aabd4e1f8b
|
df4b4848b06f2b9475c48afe65c2720c59180ff9
|
refs/heads/master
| 2022-07-16T04:51:22.226604
| 2020-05-11T13:10:34
| 2020-05-11T13:10:34
| 263,045,352
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,912
|
cpp
|
taekgun.cpp
|
#include <iostream>
using namespace std;
float player1[500] = { -1, };
float player2[500] = { -1, };
float opt_cache[500][500] = { 0, };
float diff[500][500] = { -1 };
void init(int p1, int p2) {
for (int i = 0; i < p1; i++) {
player1[i] = rand() % 100 + 30;
}
for (int j = 0; j < p2; j++) {
player2[j] = rand() % 100 + 35;
}
}
void sort(float (&player)[500], int count) {
for (int i = 0; i < count - 1; i++) {
for (int j = i + 1; j < count; j++) {
if (player[i] > player[j]) {
int value = player[i];
player[i] = player[j];
player[j] = value;
}
}
}
}
int main() {
int player1_cnt = 22;
int player2_cnt = 33;
init(player1_cnt, player2_cnt);
//for (int i = 0; i < player1_cnt; i++)
// cout << "player1 : " << player1[i] << endl;
//for (int i = 0; i < player2_cnt;i++)
// cout << "player2 : " << player2[i] << endl;
sort(player1, player1_cnt);
sort(player2, player2_cnt);
for (int i = 0; i < player1_cnt; i++)
cout << "player1 : " << player1[i] << endl;
for (int i = 0; i < player2_cnt; i++)
cout << "player2 : " << player2[i] << endl;
for (int i = 0; i < player1_cnt; i++) {
for (int j = 0; j < player2_cnt; j++) {
float tmp = player1[i] - player2[j];
if (tmp < 0)
tmp *= -1;
diff[i][j] = tmp;
}
}
for (int i = 0; i < player1_cnt; i++) {
for (int j = 0; j < player2_cnt; j++) {
cout << "diff" << i << "," << j << " : " << diff[i][j] << endl;
}
}
for (int i = 0; i < player1_cnt; i++) {
for (int j = 0; j < player2_cnt; j++) {
if (i > j) {
opt_cache[i][j] = -1;
}
else if (i == j) {
for (int k = 0; k <= i; k++) {
opt_cache[i][j] += diff[k][k];
}
}
if (j > i&& i == 0) {
int tmp = diff[0][0];
for (int i = 1; i <= j; i++) {
if (tmp > diff[0][i]) {
tmp = diff[0][i];
}
}
opt_cache[i][j] = tmp;
}
}
}
cout << "init" << endl;
for (int i = 0; i < player1_cnt; i++) {
for (int j = 0; j < player2_cnt; j++) {
cout << opt_cache[i][j] << " ";
}
cout << endl;
}
for (int i = 1; i < player1_cnt; i++) {
for (int j = 1; j < player2_cnt; j++) {
if (i < j) {
float tmp1 = opt_cache[i - 1][j - 1] + diff[i][j];
float tmp2 = opt_cache[i][j - 1];
if (tmp1 < 0 && tmp2 < 0) {
opt_cache[i][j] = -1;
}
else if (tmp2 < 0) {
opt_cache[i][j] = tmp1;
}
else if (tmp1 < 0) {
opt_cache[i][j] = tmp2;
}
else if (tmp1 > tmp2) {
opt_cache[i][j] = tmp2;
}
else {
opt_cache[i][j] = tmp1;
}
}
}
}
cout << "result" << endl;
for (int i = 0; i < player1_cnt; i++) {
for (int j = 0; j < player2_cnt; j++) {
cout << opt_cache[i][j] << " ";
}
cout << endl;
}
cout << endl;
cout << "result : " << opt_cache[player1_cnt - 1][player2_cnt - 1] << endl;
}
|
97c6fc512b67cf26cd3ab91ffb61706fa10fc5b0
|
34113a4c2d453a39edaf0de0333c2f4db1c58c08
|
/simulation/src/Maze.cpp
|
4307013a92d54dc5e8db35812e0f892bcead95bb
|
[
"MIT"
] |
permissive
|
ish591/astromania-and-simulation
|
595135fe71bda4f1d92c2654c973882161a3b506
|
a98650a03bdb11fd9a329ff85fcc9d0d2036aa83
|
refs/heads/main
| 2023-06-28T17:39:31.098986
| 2021-05-19T16:08:18
| 2021-05-19T16:08:18
| 390,024,249
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 3,940
|
cpp
|
Maze.cpp
|
#include "Maze.h"
Maze::Maze(int N, int w, int h, bool discrete_walls)
{
generate(N);
int x = min(w, h);
Maze::discrete_walls = discrete_walls;
block_size = x / M - discrete_walls;
left_offset = (w - block_size * M) / 2;
top_offset = (h - block_size * M) / 2;
}
void Maze::generate(int N)
{
// Using DFS to generate a line boundary maze and then convert it to block walls
Maze::N = N;
M = 2 * N + 1;
maze.clear();
maze = vector<vector<Box>>();
for (int i = 0; i < M; i++)
{
vector<Box> temp;
for (int j = 0; j < M; j++)
{
Box new_box = Box(0);
temp.push_back(new_box);
}
maze.push_back(temp);
}
int a[N][N][5];
srand(time(0));
for (int i = 0; i < N; i++)
{
for (int j = 0; j < N; j++)
{
for (int k = 0; k < 5; k++)
a[i][j][k] = 0;
}
}
int par = 50;
stack<pair<int, int>> st;
st.push({0, 0});
while (!st.empty())
{
int i = st.top().first;
int j = st.top().second;
int x[] = {0, 0, 0, 0};
int ct = 0;
a[i][j][0] = 1;
if (i - 1 >= 0 && a[i - 1][j][0] == 0)
{
x[ct++] = 1;
}
if (j - 1 >= 0 && a[i][j - 1][0] == 0)
{
x[ct++] = 2;
}
if (i + 1 < N && a[i + 1][j][0] == 0)
{
x[ct++] = 3;
}
if (j + 1 < N && a[i][j + 1][0] == 0)
{
x[ct++] = 4;
}
if (ct == 0)
{
st.pop();
continue;
}
int r = rand() % ct;
int l = x[r];
a[i][j][l] = 1;
if (l == 1)
{
st.push({i - 1, j});
a[i - 1][j][3] = 1;
}
else if (l == 2)
{
st.push({i, j - 1});
a[i][j - 1][4] = 1;
}
else if (l == 3)
{
st.push({i + 1, j});
a[i + 1][j][1] = 1;
}
else
{
st.push({i, j + 1});
a[i][j + 1][2] = 1;
}
}
// Make block walls
for (int i = 0; i < N; i++)
{
for (int j = 0; j < N; j++)
{
int x = 2 * i + 1, y = 2 * j + 1;
maze[x][y].update(0);
maze[x - 1][y].update(1 - a[i][j][1]);
maze[x][y - 1].update(1 - a[i][j][2]);
maze[x + 1][y].update(1 - a[i][j][3]);
maze[x][y + 1].update(1 - a[i][j][4]);
maze[x - 1][y - 1].update(2);
maze[x + 1][y - 1].update(2);
maze[x - 1][y + 1].update(2);
maze[x + 1][y + 1].update(2);
}
for (int i = 0; i < M; i++)
{
maze[i][0].update(2);
maze[0][i].update(2);
maze[i][M - 1].update(2);
maze[M - 1][i].update(2);
}
}
// for (int i = 0; i < N; i++)
// {
// for (int j = 0; j < N; j++)
// {
// cout << a[i][j][0] << a[i][j][1] << a[i][j][2] << a[i][j][3] << a[i][j][4] << " ";
// }
// cout << endl;
// }
}
void update(vector<pair<int, int>>)
{
return;
}
vector<vector<Box>> Maze::getMaze()
{
return maze;
}
int Maze::getSize()
{
return M;
}
void Maze::print()
{
for (int i = 0; i < M; i++)
{
for (int j = 0; j < M; j++)
{
cout << maze[i][j].get_block_type();
}
cout << endl;
}
}
void Maze::render(SDL_Renderer *renderer, SDL_Surface *surface, vector<SDL_Surface *> &block_surface)
{
for (int i = 0; i < M; i++)
{
for (int j = 0; j < M; j++)
{
maze[i][j].render(renderer, surface, j * (block_size) + left_offset, i * (block_size) + top_offset, block_size - discrete_walls, block_size - discrete_walls, block_surface);
}
}
}
int Maze::getBlockSize()
{
return block_size;
}
|
a9abf610651eb2e4e5e94c02be3d590ac25fe18a
|
8d2f4d737d012ba77586a3fb8002f3deb2867961
|
/fifider/Display.cpp
|
908c54f29c817bf9e23a6d49a6fbcfb44e7cd488
|
[] |
no_license
|
rgcalsaverini/fifider
|
432c9252ac1b68b51f4b373100f55e7d3ac3fb13
|
c24e69c12cd5872e313ff46d9eb754aa14b32153
|
refs/heads/master
| 2021-01-10T05:12:01.020814
| 2016-02-19T22:43:30
| 2016-02-19T22:43:30
| 51,803,922
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,600
|
cpp
|
Display.cpp
|
#include "Display.hpp"
Display& Display::getInstance(void){
static Display instance;
return instance;
}
void Display::initialize(void) {
_data_pin = HW_SR_DATA_PIN;
_clock_pin = HW_SR_CLOCK_PIN;
_latch_pin = HW_SR_LATCH_PIN;
_num_digits = HW_DISP_DIGITS;
pinMode(_clock_pin, OUTPUT);
pinMode(_latch_pin, OUTPUT);
pinMode(_data_pin, OUTPUT);
_segment_map[0]= 0x3F;
_segment_map[1]= 0x06;
_segment_map[2]= 0x5B;
_segment_map[3]= 0x4F;
_segment_map[4]= 0x66;
_segment_map[5]= 0x6D;
_segment_map[6]= 0x7D;
_segment_map[7]= 0x07;
_segment_map[8]= 0x7F;
_segment_map[9]= 0x67;
_segment_map[10] /* A */ = 0x77;
_segment_map[11] /* b */ = 0x7C;
_segment_map[12] /* C */ = 0x39;
_segment_map[13] /* d */ = 0x5E;
_segment_map[14] /* E */ = 0x79;
_segment_map[15] /* F */ = 0x71;
}
void Display::shiftByte(unsigned char data) {
int i;
int pin_state;
for (i=7; i>=0; i--) {
digitalWrite(_clock_pin, 0);
pin_state = data & (1<<i);
digitalWrite(_data_pin, pin_state);
digitalWrite(_clock_pin, 1);
digitalWrite(_data_pin, 0);
}
digitalWrite(_clock_pin, 0);
}
void Display::out(void){
for(int i = 0 ; i < _num_digits ; i++){
digitOut(i);
}
}
void Display::digitOut(unsigned char digit) {
digitalWrite(_latch_pin, 0);
shiftByte(1<<digit);
shiftByte(_digit_data[digit]);
digitalWrite(_latch_pin, 1);
}
void Display::setDigit(unsigned int idx, int num){
int data = 0;
_digit_data[idx] = _segment_map[num];
}
|
d6aade1df17521c731b7e7ada5148996d49f610b
|
d81a9ef64fcccd532dcc0dae3235b709a2ff4ebe
|
/CodeForces/StairsAndElevators/main.cpp
|
8af4f9683208c8f5a998b7cd69b6556b9fce4405
|
[] |
no_license
|
Rodrigo61/GUAXINIM
|
6d52b0b29dd736ce40295f7e7b3f7dd4c1d2396d
|
696d1077bf69bcff10cb5c07bb68dd3452952228
|
refs/heads/master
| 2021-04-09T14:29:54.226309
| 2020-11-17T01:18:21
| 2020-11-17T01:18:21
| 125,520,161
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 5,533
|
cpp
|
main.cpp
|
using namespace std;
bool debug = false;
//<editor-fold desc="GUAXINIM TEMPLATE">
/******** All Required Header Files ********/
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <sstream>
#include <queue>
#include <deque>
#include <bitset>
#include <iterator>
#include <list>
#include <stack>
#include <map>
#include <set>
#include <functional>
#include <numeric>
#include <utility>
#include <limits>
#include <time.h>
#include <math.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <assert.h>
using namespace std;
#define all(container) container.begin(), container.end()
#define mp(i,j) make_pair(i,j)
#define space " "
typedef pair<int,int> pii;
typedef long long ll;
typedef vector<ll> vll;
typedef vector<int> vi;
typedef vector<pii> vii;
/// Debug Start
template<class T1> void deb(T1 e1)
{
if(debug) {
cout << "[DEBUG]";
cout << e1 << endl;
}
}
template<class T1,class T2> void deb(T1 e1, T2 e2)
{
if(debug) {
cout << "[DEBUG]";
cout << e1 << space << e2 << endl;
}
}
template<class T1,class T2,class T3> void deb(T1 e1, T2 e2, T3 e3)
{
if(debug) {
cout << "[DEBUG]";
cout << e1 << space << e2 << space << e3 << endl;
}
}
template<class T1,class T2,class T3,class T4> void deb(T1 e1, T2 e2, T3 e3, T4 e4)
{
if(debug) {
cout << "[DEBUG]";
cout << e1 << space << e2 << space << e3 << space << e4 << endl;
}
}
template<class T1,class T2,class T3,class T4,class T5> void deb(T1 e1, T2 e2, T3 e3, T4 e4, T5 e5)
{
if(debug) {
cout << "[DEBUG]";
cout << e1 << space << e2 << space << e3 << space << e4 << space << e5 << endl;
}
}
template<class T1,class T2,class T3,class T4,class T5,class T6> void deb(T1 e1, T2 e2, T3 e3, T4 e4 ,T5 e5, T6 e6)
{
if(debug) {
cout << "[DEBUG]";
cout << e1 << space << e2 << space << e3 << space << e4 << space << e5 << space << e6 << endl;
}
}
template<typename T>
void print_vector_debug(const T& t) {
if(debug) {
cout << "[DEBUG] VECTOR:";
for (auto i = t.cbegin(); i != t.cend(); ++i) {
if ((i + 1) != t.cend()) {
cout << *i << " ";
} else {
cout << *i << endl;
}
}
}
}
template<typename T>
void print_array_debug(const T arr, int size){
if(debug) {
cout << "[DEBUG] VECTOR:";
for (int i = 0; i < size; ++i) {
cout << arr[i] << space;
}
cout << endl;
}
}
template<typename T>
void print_2Darray_debug(const T arr, int rows, int cols){
if(debug) {
cout << "[DEBUG] Matrix:" << endl;
for (int i = 0; i < rows; ++i) {
for (int j = 0; j < cols; ++j) {
cout << arr[i][j] << space;
}
cout << endl;
}
cout << endl;
}
}
template<typename T>
void print_matrix_debug(const T& t) {
if(debug) {
cout << "[DEBUG] MATRIX:" << endl;
for (auto i = t.cbegin(); i != t.cend(); ++i) {
for(auto j = i->cbegin(); j != i->cend(); ++j){
cout << *j << " ";
}
cout << endl;
}
}
}
//</editor-fold>
int main(){
ios_base::sync_with_stdio(false);
cin.tie(0);
ll R, C;
ll n_ladders, n_elevators;
ll elevator_speed;
cin >> R >> C >> n_ladders >> n_elevators >> elevator_speed;
vi ladders(n_ladders);
for (size_t i = 0; i < n_ladders; i++) {
cin >> ladders[i];
--ladders[i];
}
vi elevators(n_elevators);
for (size_t i = 0; i < n_elevators; i++) {
cin >> elevators[i];
--elevators[i];
}
ll n_querys;
cin >> n_querys;
ll i_s, j_s, i_t, j_t;
for (size_t i = 0; i < n_querys; i++) {
cin >> i_s >> j_s >> i_t >> j_t;
--i_s, --j_s, --i_t, --j_t;
ll min_dist = numeric_limits<ll>::max();
ll rows_diff = abs(i_t - i_s);
// left ladder
auto it = lower_bound(all(ladders), j_s);
if (it != ladders.begin()) {
--it;
if (*it < j_s) {
ll total_dist = abs(j_s - *it);
total_dist += rows_diff;
total_dist += abs(j_t - *it);
min_dist = min(min_dist, total_dist);
}
}
// left elevator
it = lower_bound(all(elevators), j_s);
if (it != elevators.begin()) {
--it;
if (*it < j_s) {
ll total_dist = abs(j_s - *it);
total_dist += ceil((double)rows_diff / elevator_speed);
total_dist += abs(j_t - *it);
min_dist = min(min_dist, total_dist);
}
}
// right ladder
it = upper_bound(all(ladders), j_s);
if (it != ladders.end()) {
ll total_dist = abs(j_s - *it);
total_dist += rows_diff;
total_dist += abs(j_t - *it);
min_dist = min(min_dist, total_dist);
}
// right elevator
it = upper_bound(all(elevators), j_s);
if (it != elevators.end()) {
ll total_dist = abs(j_s - *it);
total_dist += ceil((double)rows_diff / elevator_speed);
total_dist += abs(j_t - *it);
min_dist = min(min_dist, total_dist);
}
if (rows_diff == 0) {
min_dist = abs(j_t - j_s);
}
cout << min_dist << endl;
}
return 0;
}
|
b554c8ecb057aee0d7c4026133ff84f758a57e9a
|
e11b2493f55c60685c3ea76f900be73e6a454b2f
|
/C++ Primer/15_Object_Oriented_Programming/15_4.cpp
|
393abd2670a0f3cae541490302f585c2afd09e0c
|
[] |
no_license
|
zpoint/Reading-Exercises-Notes
|
29e566dd86d97eadb84d7bb6f8f640b85486557c
|
31b38fe927232ba8e6f6a0e7ab9c58026eefcffb
|
refs/heads/master
| 2021-06-04T08:12:42.777309
| 2021-04-19T02:12:22
| 2021-04-19T02:12:22
| 70,507,489
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 185
|
cpp
|
15_4.cpp
|
#include <iostream>
class Base {
};
// class Derived : public Derived { };
class Derived : private Base { };
class Derived2 : public Base { };
int main()
{
Base b;
return 0;
}
|
fcdc53847c1d0cc8716493fae4fe1996f4436346
|
8583b5bfc594b994f51d24d012e92ae66bf2e5ea
|
/src/BabylonImGui/include/babylon/inspector/components/actiontabs/tabs/propertygrids/materials/standard_material_property_grid_component.h
|
82123f906f8a1b71f4fe3e0ac2f7daee09ad23d2
|
[
"LicenseRef-scancode-free-unknown",
"Apache-2.0"
] |
permissive
|
samdauwe/BabylonCpp
|
84b8e51b59f04a847681a97fa6fe0a5c554e9e1f
|
3dad13a666299cbcf2e2db5b24575c19743e1000
|
refs/heads/master
| 2022-01-09T02:49:55.057544
| 2022-01-02T19:27:12
| 2022-01-02T19:27:12
| 77,682,359
| 309
| 41
|
Apache-2.0
| 2020-11-06T12:16:17
| 2016-12-30T11:29:05
|
C++
|
UTF-8
|
C++
| false
| false
| 8,387
|
h
|
standard_material_property_grid_component.h
|
#ifndef BABYLON_INSPECTOR_COMPONENTS_ACTION_TABS_TABS_PROPERTY_GRIDS_MATERIALS_STANDARD_MATERIAL_PROPERTY_GRID_COMPONENT_H
#define BABYLON_INSPECTOR_COMPONENTS_ACTION_TABS_TABS_PROPERTY_GRIDS_MATERIALS_STANDARD_MATERIAL_PROPERTY_GRID_COMPONENT_H
#include <babylon/babylon_api.h>
#include <babylon/inspector/components/actiontabs/lines/check_box_line_component.h>
#include <babylon/inspector/components/actiontabs/lines/color3_line_component.h>
#include <babylon/inspector/components/actiontabs/lines/slider_line_component.h>
#include <babylon/inspector/components/actiontabs/lines/texture_link_line_component.h>
#include <babylon/inspector/components/actiontabs/tabs/propertygrids/materials/common_material_property_grid_component.h>
#include <babylon/materials/detail_map_configuration.h>
#include <babylon/materials/standard_material.h>
#include <babylon/materials/textures/base_texture.h>
namespace BABYLON {
struct BABYLON_SHARED_EXPORT StandardMaterialPropertyGridComponent {
static void renderTextures(const StandardMaterialPtr& material)
{
if (material->getActiveTextures().empty()) {
return;
}
// --- TEXTURES ---
static auto texturesContainerOpened = true;
ImGui::SetNextTreeNodeOpen(texturesContainerOpened, ImGuiCond_Always);
if (ImGui::CollapsingHeader("TEXTURES")) {
TextureLinkLineComponent::render("Diffuse", material, material->diffuseTexture());
TextureLinkLineComponent::render("Specular", material, material->specularTexture());
TextureLinkLineComponent::render("Reflection", material, material->reflectionTexture());
TextureLinkLineComponent::render("Refraction", material, material->refractionTexture());
TextureLinkLineComponent::render("Emissive", material, material->emissiveTexture());
TextureLinkLineComponent::render("Bump", material, material->bumpTexture());
TextureLinkLineComponent::render("Opacity", material, material->opacityTexture());
TextureLinkLineComponent::render("Ambient", material, material->ambientTexture());
TextureLinkLineComponent::render("Lightmap", material, material->lightmapTexture());
TextureLinkLineComponent::render("Detailmap", material, material->detailMap->texture());
if (CheckBoxLineComponent::render("Use lightmap as shadowmap",
material->useLightmapAsShadowmap())) {
material->useLightmapAsShadowmap = !material->useLightmapAsShadowmap();
}
if (CheckBoxLineComponent::render("Use detailmap", material->detailMap->isEnabled())) {
material->detailMap->isEnabled = !material->detailMap->isEnabled();
}
texturesContainerOpened = true;
}
else {
texturesContainerOpened = false;
}
}
static void render(const StandardMaterialPtr& material)
{
CommonMaterialPropertyGridComponent::render(material);
renderTextures(material);
// --- LIGHTING & COLORS ---
static auto lightingAndColorsOpened = true;
ImGui::SetNextTreeNodeOpen(lightingAndColorsOpened, ImGuiCond_Always);
if (ImGui::CollapsingHeader("LIGHTING & COLORS")) {
Color3LineComponent::render("Diffuse", material->diffuseColor);
Color3LineComponent::render("Specular", material->specularColor);
auto sliderChange = SliderLineComponent::render("Specular power", material->specularPower,
0.f, 128.f, 0.1f, "%.2f");
if (sliderChange) {
material->specularPower = sliderChange.value();
}
Color3LineComponent::render("Emissive", material->emissiveColor);
Color3LineComponent::render("Ambient", material->ambientColor);
if (CheckBoxLineComponent::render("Use specular over alpha",
material->useSpecularOverAlpha())) {
material->useSpecularOverAlpha = !material->useSpecularOverAlpha();
}
lightingAndColorsOpened = true;
}
else {
lightingAndColorsOpened = false;
}
// --- LEVELS ---
static auto levelsOpened = false;
ImGui::SetNextTreeNodeOpen(levelsOpened, ImGuiCond_Always);
if (ImGui::CollapsingHeader("LEVELS")) {
if (material->diffuseTexture()) {
auto sliderChange = SliderLineComponent::render(
"Diffuse level", material->diffuseTexture()->level, 0.f, 2.f, 0.01f, "%.2f");
if (sliderChange) {
material->diffuseTexture()->level = sliderChange.value();
}
}
if (material->specularTexture()) {
auto sliderChange = SliderLineComponent::render(
"Specular level", material->specularTexture()->level, 0.f, 2.f, 0.01f, "%.2f");
if (sliderChange) {
material->specularTexture()->level = sliderChange.value();
}
}
if (material->reflectionTexture()) {
auto sliderChange = SliderLineComponent::render(
"Reflection level", material->reflectionTexture()->level, 0.f, 2.f, 0.01f, "%.2f");
if (sliderChange) {
material->reflectionTexture()->level = sliderChange.value();
}
}
if (material->refractionTexture()) {
auto sliderChange = SliderLineComponent::render(
"Refraction level", material->refractionTexture()->level, 0.f, 2.f, 0.01f, "%.2f");
if (sliderChange) {
material->refractionTexture()->level = sliderChange.value();
}
}
if (material->emissiveTexture()) {
auto sliderChange = SliderLineComponent::render(
"Emissive level", material->emissiveTexture()->level, 0.f, 2.f, 0.01f, "%.2f");
if (sliderChange) {
material->emissiveTexture()->level = sliderChange.value();
}
}
if (material->bumpTexture()) {
auto sliderChange = SliderLineComponent::render(
"Bump level", material->bumpTexture()->level, 0.f, 2.f, 0.01f, "%.2f");
if (sliderChange) {
material->bumpTexture()->level = sliderChange.value();
}
}
if (material->opacityTexture()) {
auto sliderChange = SliderLineComponent::render(
"Opacity level", material->opacityTexture()->level, 0.f, 2.f, 0.01f, "%.2f");
if (sliderChange) {
material->opacityTexture()->level = sliderChange.value();
}
}
if (material->ambientTexture()) {
auto sliderChange = SliderLineComponent::render(
"Ambient level", material->ambientTexture()->level, 0.f, 2.f, 0.01f, "%.2f");
if (sliderChange) {
material->ambientTexture()->level = sliderChange.value();
}
}
if (material->lightmapTexture()) {
auto sliderChange = SliderLineComponent::render(
"Lightmap level", material->lightmapTexture()->level, 0.f, 2.f, 0.01f, "%.2f");
if (sliderChange) {
material->lightmapTexture()->level = sliderChange.value();
}
}
if (material->detailMap->isEnabled()) {
auto sliderChange = SliderLineComponent::render(
"Detailmap diffuse", material->detailMap->diffuseBlendLevel, 0.f, 1.f, 0.01f, "%.2f");
if (sliderChange) {
material->detailMap->diffuseBlendLevel = sliderChange.value();
}
sliderChange = SliderLineComponent::render("Detailmap bump", material->detailMap->bumpLevel,
0.f, 1.f, 0.01f, "%.2f");
if (sliderChange) {
material->detailMap->bumpLevel = sliderChange.value();
}
}
levelsOpened = true;
}
else {
levelsOpened = false;
}
// --- NORMAL MAP ---
static auto normalMapOpened = false;
ImGui::SetNextTreeNodeOpen(normalMapOpened, ImGuiCond_Always);
if (ImGui::CollapsingHeader("NORMAL MAP")) {
if (CheckBoxLineComponent::render("Invert X axis", material->invertNormalMapX())) {
material->invertNormalMapX = !material->invertNormalMapX();
}
if (CheckBoxLineComponent::render("Invert Y axis", material->invertNormalMapY())) {
material->invertNormalMapY = !material->invertNormalMapY();
}
normalMapOpened = true;
}
else {
normalMapOpened = false;
}
}
}; // end of struct StandardMaterialPropertyGridComponent
} // end of namespace BABYLON
#endif // end of
// BABYLON_INSPECTOR_COMPONENTS_ACTION_TABS_TABS_PROPERTY_GRIDS_MATERIALS_STANDARD_MATERIAL_PROPERTY_GRID_COMPONENT_H
|
208cbd830d0def1d0f8b940b1d90a269da2c8094
|
fb7926a5074f9d1d63b53a3822b70de61ff50b3b
|
/node_create/create_unsqueeze_node.hpp
|
cb83bed0deb5367947f084d65fc621b6e6d92094
|
[] |
no_license
|
wite-chen/tensorrt_wrapper_for_onnx
|
1b54a99266f65fb11500f334022b4ff3c2b84bd5
|
31f9dffc70e9c055663ba6218391bb363b9ced7b
|
refs/heads/master
| 2022-11-05T16:16:33.553202
| 2020-06-28T07:19:47
| 2020-06-28T07:19:47
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 434
|
hpp
|
create_unsqueeze_node.hpp
|
#ifndef __CREATE_UNSQUEEZE_NODE_HPP__
#define __CREATE_UNSQUEEZE_NODE_HPP__
namespace tensorrtInference
{
extern nvinfer1::ILayer* createUnsqueezeNode(nvinfer1::INetworkDefinition* network, std::map<std::string, nvinfer1::ITensor*>& tensors,
tensorrtInference::nodeInfo* nodeConfInfo, std::map<std::string, tensorrtInference::weightInfo>& nodeWeightsInfo);
} //tensorrtInference
#endif //__CREATE_UNSQUEEZE_NODE_HPP__
|
4c6684de4fe987f0f540449621f3f302231efbf1
|
45e0fbd9a9dbcdd4fbe6aaa2fdb2aed296f81e33
|
/FindSecret/Classes/Native/UnityEngine_UnityEngine_RangeAttribute3337244227.h
|
7b05cd542f38ed5b58e0118dbd775644c9c68347
|
[
"MIT"
] |
permissive
|
GodIsWord/NewFindSecret
|
d4a5d2d810ee1f9d6b3bc91168895cc808bac817
|
4f98f316d29936380f9665d6a6d89962d9ee5478
|
refs/heads/master
| 2020-03-24T09:54:50.239014
| 2018-10-27T05:22:11
| 2018-10-27T05:22:11
| 142,641,511
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,305
|
h
|
UnityEngine_UnityEngine_RangeAttribute3337244227.h
|
#pragma once
#include "il2cpp-config.h"
#ifndef _MSC_VER
# include <alloca.h>
#else
# include <malloc.h>
#endif
#include <stdint.h>
#include "UnityEngine_UnityEngine_PropertyAttribute3677895545.h"
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// UnityEngine.RangeAttribute
struct RangeAttribute_t3337244227 : public PropertyAttribute_t3677895545
{
public:
// System.Single UnityEngine.RangeAttribute::min
float ___min_1;
// System.Single UnityEngine.RangeAttribute::max
float ___max_2;
public:
inline static int32_t get_offset_of_min_1() { return static_cast<int32_t>(offsetof(RangeAttribute_t3337244227, ___min_1)); }
inline float get_min_1() const { return ___min_1; }
inline float* get_address_of_min_1() { return &___min_1; }
inline void set_min_1(float value)
{
___min_1 = value;
}
inline static int32_t get_offset_of_max_2() { return static_cast<int32_t>(offsetof(RangeAttribute_t3337244227, ___max_2)); }
inline float get_max_2() const { return ___max_2; }
inline float* get_address_of_max_2() { return &___max_2; }
inline void set_max_2(float value)
{
___max_2 = value;
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
|
ed06f7e6afd6ee3f7f4de1a25570cac1cde3bb9e
|
76ce3aee345f034e4ff859884c6d956695c437b7
|
/gta5-extended-video-export/script.h
|
d06a74b556e0b4cd8e32003d691afb16209d7813
|
[
"Apache-2.0"
] |
permissive
|
garudht/gta5-extended-video-export
|
27ea89ebb1fbf78f14f21442188c733095f7db53
|
218188b00932aaff197de5120c0c7a6887942d49
|
refs/heads/master
| 2021-01-18T07:53:10.198586
| 2017-02-14T15:42:19
| 2017-02-14T15:42:19
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 758
|
h
|
script.h
|
#pragma once
#include <dxgi.h>
#include <d3d11.h>
#include <wrl.h>
using namespace Microsoft::WRL;
template <class T> void SafeRelease(T **ppT)
{
if (*ppT)
{
(*ppT)->Release();
*ppT = NULL;
}
}
template <class B, class A> B ForceCast(A a) {
union {
A a;
B b;
} x;
x.a = a;
return x.b;
}
void initialize();
void ScriptMain();
void onPresent(IDXGISwapChain *swapChain);
void finalize();
static void prepareDeferredContext(ComPtr<ID3D11Device> pDevice, ComPtr<ID3D11DeviceContext> pContext);
static ComPtr<ID3D11Texture2D> divideBuffer(ComPtr<ID3D11Device> pDevice, ComPtr<ID3D11DeviceContext> pContext, uint32_t k);
static void drawAdditive(ComPtr<ID3D11Device> pDevice, ComPtr<ID3D11DeviceContext> pContext, ComPtr<ID3D11Texture2D> pSource);
|
42b50dcf081c214436a8d35ad9340d828daf7c75
|
92548377fb4a91af7cc56570242aa3168cc6c9c6
|
/BOJ/0To5000/1766.cpp
|
859e809bce4c24358388d08f3aba62029816b7ef
|
[] |
no_license
|
LaLlorona/Algorithms
|
d993a05f5dbc22850d0f6a061a5f35ecff5f8af3
|
6d02a9552c22acefa58686e909bc8ae0479a6e4b
|
refs/heads/master
| 2023-05-24T17:37:14.993992
| 2023-05-17T05:33:14
| 2023-05-17T05:33:14
| 220,796,924
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,048
|
cpp
|
1766.cpp
|
#include <bits/stdc++.h>
//#include <iostream>
//#include <queue>
//#include <vector>
using namespace std;
const int MAX = 32001;
vector<int> graph[MAX];
int num_pointed[MAX];
int num_problems, num_information;
void PrintBestOrder() {
priority_queue<int, vector<int>, greater<int> > pq;
for (int i = 0; i < num_problems; i++) {
if (num_pointed[i] == 0) {
pq.push(i);
}
}
while (!pq.empty()) {
int here = pq.top();
cout << here + 1 << " ";
pq.pop();
for (int i = 0; i < graph[here].size(); i++) {
int there = graph[here][i];
num_pointed[there] = num_pointed[there] - 1;
if (num_pointed[there] == 0) {
pq.push(there);
}
}
}
}
int main() {
std::ios_base::sync_with_stdio(false);
std::cin.tie(NULL);
std::cout.tie(NULL);
cin >> num_problems >> num_information;
for (int i = 0; i < num_information; i++) {
int first, second;
cin >> first >> second;
first = first - 1;
second = second - 1;
graph[first].push_back(second);
num_pointed[second]++;
}
PrintBestOrder();
return 0;
}
|
3b1bb05c3e00cf7840887324bea0fe456d9a6780
|
246a16842feb7633edbe6291ff36b4c93edbb3c7
|
/conan-package/lager/test_package/counter.hpp
|
a22e94c55269cd63d992a15d9ae00a045d6384d3
|
[] |
no_license
|
curtkim/c-first
|
2c223949912c708734648cf29f98778249f79346
|
f6fa50108ab7c032b74199561698cef087405c37
|
refs/heads/master
| 2023-06-08T10:57:35.159250
| 2023-05-28T05:52:20
| 2023-05-28T05:52:20
| 213,894,731
| 3
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 899
|
hpp
|
counter.hpp
|
#include <lager/debug/cereal/struct.hpp>
#include <lager/util.hpp>
#include <variant>
namespace counter {
struct model
{
int value = 0;
};
struct increment_action
{};
struct decrement_action
{};
struct reset_action
{
int new_value = 0;
};
using action = std::variant<increment_action, decrement_action, reset_action>;
inline model update(model c, action action)
{
return std::visit(lager::visitor{
[&](increment_action) { return model{c.value + 1}; },
[&](decrement_action) { return model{c.value - 1}; },
[&](reset_action a) { return model{a.new_value}; },
},
action);
}
LAGER_CEREAL_STRUCT(model, (value));
LAGER_CEREAL_STRUCT(increment_action);
LAGER_CEREAL_STRUCT(decrement_action);
LAGER_CEREAL_STRUCT(reset_action, (new_value));
} // namespace counter
|
76623a537e20c18dbe9704d3ed42ac5b2d0dcc65
|
f81b774e5306ac01d2c6c1289d9e01b5264aae70
|
/chrome/browser/privacy_budget/privacy_budget_ukm_entry_filter.cc
|
bad4cc84c0bd5823e51faaaa017dda68064418e3
|
[
"BSD-3-Clause"
] |
permissive
|
waaberi/chromium
|
a4015160d8460233b33fe1304e8fd9960a3650a9
|
6549065bd785179608f7b8828da403f3ca5f7aab
|
refs/heads/master
| 2022-12-13T03:09:16.887475
| 2020-09-05T20:29:36
| 2020-09-05T20:29:36
| 293,153,821
| 1
| 1
|
BSD-3-Clause
| 2020-09-05T21:02:50
| 2020-09-05T21:02:49
| null |
UTF-8
|
C++
| false
| false
| 3,044
|
cc
|
privacy_budget_ukm_entry_filter.cc
|
// Copyright 2020 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/privacy_budget/privacy_budget_ukm_entry_filter.h"
#include <algorithm>
#include <memory>
#include "base/containers/flat_set.h"
#include "base/rand_util.h"
#include "base/stl_util.h"
#include "base/time/time.h"
#include "chrome/browser/privacy_budget/sampled_surface_tracker.h"
#include "services/metrics/public/cpp/ukm_builders.h"
#include "services/metrics/public/mojom/ukm_interface.mojom.h"
#include "third_party/blink/public/common/privacy_budget/identifiability_study_settings.h"
#include "third_party/blink/public/common/privacy_budget/identifiable_surface.h"
PrivacyBudgetUkmEntryFilter::PrivacyBudgetUkmEntryFilter(
IdentifiabilityStudyState* state)
: identifiability_study_state_(state) {}
bool PrivacyBudgetUkmEntryFilter::FilterEntry(
ukm::mojom::UkmEntry* entry,
base::flat_set<uint64_t>* removed_metric_hashes) const {
// We don't yet deal with any event other than Identifiability. All other
// types of events pass through.
if (entry->event_hash != ukm::builders::Identifiability::kEntryNameHash)
return true;
const bool enabled = blink::IdentifiabilityStudySettings::Get()->IsActive();
// If the study is not enabled, drop all identifiability events.
if (!enabled || entry->metrics.empty())
return false;
std::vector<blink::IdentifiableSurface> sampled_surfaces;
sampled_surfaces.reserve(entry->metrics.size());
base::EraseIf(entry->metrics, [&](auto metric) {
const auto surface =
blink::IdentifiableSurface::FromMetricHash(metric.first);
// Exclude the set that are blocked from all measurements.
if (!blink::IdentifiabilityStudySettings::Get()->IsSurfaceAllowed(surface))
return true;
// Record the set of surfaces sampled by the site.
if (identifiability_study_state_->ShouldRecordSurface(entry->source_id,
surface))
sampled_surfaces.push_back(surface);
// Exclude the set that are disabled for this user
return !identifiability_study_state_->ShouldSampleSurface(surface);
});
uint64_t sample_idx = 0;
for (const auto& v : sampled_surfaces) {
// Add entries marking the surfaces that were sampled by the source as
// sampled.
blink::IdentifiableSurface s = blink::IdentifiableSurface::FromTypeAndInput(
blink::IdentifiableSurface::Type::kMeasuredSurface, sample_idx++);
entry->metrics.insert_or_assign(entry->metrics.end(), s.ToUkmMetricHash(),
v.ToUkmMetricHash());
}
// Identifiability metrics can leak information simply by being measured.
// Hence the metrics that are filtered out aren't returning in
// |removed_metric_hashes|.
return !entry->metrics.empty();
}
void PrivacyBudgetUkmEntryFilter::OnStoreRecordingsInReport() const {
identifiability_study_state_->ResetRecordedSurfaces();
}
|
f1d5712dafdc7a5ac1f35075b5e1c64b6af7755c
|
75f308823c3244bc90de37ae92e46740cdd5b67f
|
/DarknessMayKill/game/Game.hpp
|
3f133892b1d7d7af042e998d8e0fa77d242e00ee
|
[] |
no_license
|
ZwodahS/DarknessMayKill
|
cd724b5a5376cd8d922e50367f7ad27be6ee935d
|
fef1ae62e51ba4a7c56b478bbffe2a04420cbb2a
|
refs/heads/master
| 2020-12-25T19:15:25.789528
| 2014-09-07T11:09:32
| 2014-09-07T11:09:32
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,497
|
hpp
|
Game.hpp
|
#ifndef _GAME_GAME_HPP_
#define _GAME_GAME_HPP_
#include <string>
#include <SFML/Graphics.hpp>
#include <SFML/System.hpp>
#include "../zf/zf_twindow.hpp"
#include "Logger.hpp"
#include "KeyMap.hpp"
#include "ui/DisplayManager.hpp"
/**
* Game should hold all the global variable.
*/
class Game
{
//////////////////// Constants ////////////////////
public:
static const std::string ResourcePath;
static const std::string Version;
static const std::string VersionName;
static const std::string Title;
//////////////////// Core ////////////////////
public:
Game();
~Game();
void init();
void run();
const sf::Vector2i& getScreenSize() const;
const sf::Vector2i& getCoreTermSize() const;
int getCoreCellSize() const;
private:
sf::Vector2i screenSize;
int coreCellSize;
sf::Vector2i coreTermSize;
int framerate;
//////////////////// Assets ////////////////////
public:
private:
void initAssets();
//////////////////// Logger ////////////////////
public:
Logger& getLogger();
private:
Logger logger;
//////////////////// KeyMapping ////////////////////
public:
KeyMap keyMap;
private:
void initKeys();
std::vector<int> inputs;
//////////////////// UI ////////////////////
public:
void initUI();
void update(const sf::Time& delta);
void draw(const sf::Time& delta);
private:
sf::RenderWindow* renderWindow;
zf::TiledWindowFactory* tw_factory;
DisplayManager* displayManager;
};
#endif
|
46f9a798bdfa9c1770a72a6942fa183336dcaef4
|
c85621585a8622e5373d03f8e7b9e0b1cef45446
|
/game/include/player/PlayerState.hpp
|
f7fd340042f53b64721fb7460d682697ab07210d
|
[] |
no_license
|
anderer455/NeumannGame
|
c81dc201d4c118528e0ba2e2ba580af6b6afe30b
|
eb449c5882813d9602232e79e3aeac8aa7418d22
|
refs/heads/master
| 2023-05-11T02:07:39.673505
| 2021-05-30T22:23:07
| 2021-05-30T22:23:07
| 301,832,458
| 2
| 0
| null | 2021-05-06T19:51:03
| 2020-10-06T19:23:41
|
C++
|
UTF-8
|
C++
| false
| false
| 1,083
|
hpp
|
PlayerState.hpp
|
#pragma once
#include <memory>
#include <tuple>
namespace game
{
class PlayerState
{
private:
int m_ironBalance;
int m_copperBalance;
int m_siliconBalance;
int m_landConquered;
protected:
public:
PlayerState();
PlayerState(int, int, int, int);
void initializePlayerState(int, int, int, int);
void updatePlayerLandConquered();
void updatePlayerBalances(int, int, int);
bool checkBalance(int, int, int);
std::tuple<int, int, int, int> getPlayerState();
void updateLand(int value)
{
m_landConquered += value;
}
int getIronBalance()
{
return m_ironBalance;
}
void setIronBalance(int iron)
{
m_ironBalance = iron;
}
int getCopperBalance()
{
return m_copperBalance;
}
void setCopperBalance(int copper)
{
m_copperBalance = copper;
}
int getSiliconBalance()
{
return m_siliconBalance;
}
void setSiliconBalance(int silicon)
{
m_siliconBalance = silicon;
}
void setLandConquered(int land)
{
m_landConquered = land;
}
int getLandConquered()
{
return m_landConquered;
}
};
}
|
13e32ba1e8e46c6aa223942bf1017b48b9a54ac7
|
bb285e1849703530e40bfa39109d440b80b9cc88
|
/0002_Add_Two_Numbers/main.cpp
|
5cfea0dd5aa01da99361c8d372f9dcb3844a5f88
|
[] |
no_license
|
kkoala0864/LeetCode
|
43fe84a63af1605a3034b072f4cd26683af1fd85
|
386f8f17a5507f3940ad1621fd36d2ae98950727
|
refs/heads/master
| 2023-07-14T12:49:04.735378
| 2021-08-15T08:17:04
| 2021-08-15T08:17:04
| 33,233,776
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 369
|
cpp
|
main.cpp
|
#include <Solution.h>
#include <iostream>
int main() {
ListNode* l11 = new ListNode(3);
ListNode* l12 = new ListNode(7);
l11->next = l12;
ListNode* l21 = new ListNode(9);
ListNode* l22 = new ListNode(2);
l21->next = l22;
Solution test;
ListNode* ret = test.addTwoNumbers(l11,l21);
while ( ret ) {
std::cout << ret->val << std::endl;
ret = ret->next;
}
}
|
eadab0d4a7d8abbf81ca8c70d40e271fcc42bddf
|
9d23a4abfad737b1194bc80328653ecae9cbd847
|
/Motor2D/RemapingScene.h
|
eda03c719275ee740f81094190e90316c97d29d9
|
[] |
no_license
|
bubleegames/Project2_Zelda
|
8cb900144ce22e3e58c3269fe31ec62f1a3ed468
|
0ea5121e0a123db710fb2d7605c3c38ab592ca73
|
refs/heads/master
| 2020-04-29T12:01:10.692097
| 2017-06-12T09:18:23
| 2017-06-12T09:18:23
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,843
|
h
|
RemapingScene.h
|
#ifndef _REMAPINGSCENE_H_
#define _REMAPINGSCENE_H_
//
#include "Scene.h"
#include "j1Gui.h"
#include "Mapping.h"
#include "j1App.h"
#include "j1Viewports.h"
enum remaping_state
{
r_s_state_null,
r_s_confirm,
r_s_back,
r_s_minimap,
r_s_shop,
r_s_a1,
r_s_a2,
r_s_a3,
r_s_a4,
r_s_inside,
};
struct remap_ui
{
UI_Image* confirm_key = nullptr;
UI_Image* back_key = nullptr;
UI_Image* minimap_key = nullptr;
UI_Image* shop_key = nullptr;
UI_Image* a1_key = nullptr;
UI_Image* a2_key = nullptr;
UI_Image* a3_key = nullptr;
UI_Image* a4_key = nullptr;
UI_Image* confirm_background = nullptr;
UI_Image* back_background = nullptr;
UI_Image* minimap_background = nullptr;
UI_Image* shop_background = nullptr;
UI_Image* a1_background = nullptr;
UI_Image* a2_background = nullptr;
UI_Image* a3_background = nullptr;
UI_Image* a4_background = nullptr;
UI_Text* confirm_text = nullptr;
UI_Text* back_text = nullptr;
UI_Text* minimap_text = nullptr;
UI_Text* shop_text = nullptr;
UI_Text* a1_text = nullptr;
UI_Text* a2_text = nullptr;
UI_Text* a3_text = nullptr;
UI_Text* a4_text = nullptr;
UI_Image* a = nullptr;
UI_Image* b = nullptr;
UI_Image* x = nullptr;
UI_Image* y = nullptr;
UI_Image* rb = nullptr;
UI_Image* lb = nullptr;
UI_Image* rt = nullptr;
UI_Image* lt = nullptr;
UI_Image* cursor = nullptr;
UI_Image* button_selector_cursor = nullptr;
UI_Image* button_support = nullptr;
UI_Image* support_pick = nullptr;
remaping_state current_state = r_s_confirm;
remaping_state prev_state = r_s_confirm;
int curr_inside_pos = -1;
vector<key_mapping> sdl_code;
};
class RemapingScene : public Scene
{
public:
RemapingScene();
~RemapingScene();
bool Start();
bool Update(float dt);
bool CleanUp();
UI_Window* window = nullptr;
private:
// Gets the position of the cursor depending on what the state is
iPoint GetCursorPosFromCurrentState(remaping_state curr_state);
// Change the current key content
void UpdateKeys(int i);
// Executed when the player press A to open the list of avalible buttons
void EnterOption(int i);
// Hides button selection information
void QuitOption(int i);
// Check what buttons have to appear and puts them in the support
void OpenFreeButtonList(int i);
// Check if it's a button or a back-triger
bool IsButton(int id);
void SetButtonsFromID(key_mapping curr_key, int viewport);
void MoveSelectorCursor(bool up, int viewport);
void RemapKey(remaping_state curr_state, int sdl_scancode, bool isbutton, int viewport);
private:
remap_ui remapping_ui[4];
SDL_Texture* background_image = nullptr;
bool inside = false;
};
#endif
|
4611ae6b5dbc6ae4a8ccacc7ed0027a4ad4fed6a
|
d6e6dc8c0b72531906dfd77ed2a4a14dccd6786c
|
/CodeBlocks stateMachine/stateMachine/src/Display.cpp
|
e0036ecfb9c1d2701486a57f4e74e7126b7dc73e
|
[] |
no_license
|
Slynott/Portfolio-Task2
|
2aefd5984324a39751bd20fbc2dced2570722c70
|
903436b88c8a53ff8c27797472eb98069b776c20
|
refs/heads/master
| 2021-01-12T10:13:30.981787
| 2017-01-05T11:21:07
| 2017-01-05T11:21:07
| 76,390,170
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 221
|
cpp
|
Display.cpp
|
//Display.cpp
#include "Display.h"
using namespace std;
Display::Display()
{
//ctor
}
Display::~Display()
{
//dtor
}
void getDisplay()
{
}
void setDisplay()
{
void removeDisplay();
return 0;
}
|
d66bf1c9f1dae5c2064204cb423c21b81b81b262
|
a95168206dfdd91350f339095dbc24acf8f206bf
|
/veiculo.cpp
|
ddd1660856380db7482105099b3e91ec8950d59b
|
[] |
no_license
|
jvbazzanella/Trabalho2
|
c7908fda67d2dacacb840beb564e71741088c13d
|
5fedcc24708cf783ba97e350d5100cf3d5146a53
|
refs/heads/master
| 2020-05-03T18:33:02.229143
| 2019-04-30T20:42:21
| 2019-04-30T20:42:21
| 178,764,970
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 887
|
cpp
|
veiculo.cpp
|
#include <iostream>
#include <iomanip>
#include "veiculo.h"
#include <string>
using namespace std;
Veiculo::Veiculo(string m, int cav, int cap, string pla) : marca(m), potencia(cav), capacidade(cap), placa(pla) {}
string Veiculo::getMarca() const {
return marca;
}
int Veiculo::getPotencia() const {
return potencia;
}
int Veiculo::getCapacidade() const {
return capacidade;
}
string Veiculo::getPlaca() const {
return placa;
}
void Veiculo::setMarca(string m) {
marca=m;
}
void Veiculo::setPotencia(int cav) {
potencia=cav;
}
void Veiculo::setCapacidade(int cap){
capacidade=cap;
}
void Veiculo::setPlaca(string pla){
placa=pla;
}
int Veiculo::getHash(int max_number) const{
int temp=1;
for (unsigned i=0; i<4; ++i){
temp *= marca.at(i);
}
return ((temp + capacidade + potencia) / 100)%max_number;
}
|
cfafcbe597a9ef05ea5c1080493a9229ff9e5bf3
|
131b5f4936f501c58b38c169ee4aeb8880c0029d
|
/BIB_20Nov2020_Projet_SMA/GestionAgents/LibMoRis/src/Agent.cpp
|
75eaeda2f900b4a92861186cca8db74c3f5133ed
|
[] |
no_license
|
IliasMAOUDJ/Agent-Based-Edge-Detection
|
d25ea5c888656169763c080703f31ca28ac5a5e5
|
d11c08c3e27175f02635761ade1605ee64607c2b
|
refs/heads/main
| 2023-02-27T19:48:46.813340
| 2021-02-06T15:44:12
| 2021-02-06T15:44:12
| 319,971,399
| 1
| 0
| null | 2021-01-05T22:35:23
| 2020-12-09T13:52:21
|
C++
|
UTF-8
|
C++
| false
| false
| 19,154
|
cpp
|
Agent.cpp
|
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include "Agent.h"
#include <sstream>
//--
Agent::Agent(void)
{
_theAgentsSched = NULL;
_name = ""; // L'agent n'a pas encore de nom
_baseClass = ""; // ni de classe de base
_class = ""; // ni de classe
_deadAgent = false; // cf void newAgent(Agent* This)
_nbMessages = 0;
_liveMethod = NULL;
_isSuspended = false;
newAgent();
}
//--
Agent::Agent(const Agent& anAgent)
{
_theAgentsSched = NULL;
_name = ""; // L'agent n'a pas encore de nom
_baseClass = ""; // ni de classe de base
_class = ""; // ni de classe
_deadAgent = false; // cf void newAgent(Agent* This)
_copy(anAgent); // Recopie de la boite _mailBox + gestion _sensitivity
// + _isSuspended + _liveMethod
newAgent();
}
//--
Agent& Agent::operator=(const Agent& anAgent)
{
if (this != &anAgent)
{
_destroy(); // Destruction de la boite _mailBox + gestion _sensitivity
_copy(anAgent); // Recopie de la boite _mailBox + gestion _sensitivity
// + _isSuspended + _liveMethod
}
return *this;
}
//--
Agent::~Agent(void)
{
if (_theAgentsSched) _theAgentsSched->removeInstance(this,_agentsClasses);
_agentsClasses.clear();
_destroy(); // Destruction de la boite _mailBox + gestion _sensitivity
}
//--
void Agent::newAgent(void)
{
if (_deadAgent) return;
_theAgentsSched = Scheduler::getCurrentSched();
if(_theAgentsSched==NULL)
{
cerr << ">---------------------------------" << endl;
cerr << "Error: void Agent::newAgent(void),\n"
<< "there is no Scheduler !!" << endl;
cerr << "Stop..." << endl;
cerr << "<---------------------------------" << endl;
exit(1);
}
_baseClass = _class;
_class = getClassName(); // Voir DEFCLASS
if (_baseClass!=_class)
{ // Histoire d'avoir l'arbre d'heritage,
_agentsClasses.push_back(_class); // on enregistre la classe
_theAgentsSched->decNextInstanceNumber(_baseClass);
unsigned long instanceNumber =
_theAgentsSched->getNextInstanceNumber(_class);
setName(instanceNumber);
_theAgentsSched->addNewInstance(this,_class);
}
}
//--
void Agent::newAgent(Agent *This) // This (pour l'heritage multiple)
{
if (_deadAgent) return;
if (This == NULL || this == This) newAgent(); // Cas heritage simple
else { // if (this != This) // Cas heritage multiple !
_theAgentsSched = Scheduler::getCurrentSched();
if(_theAgentsSched==NULL)
{
cerr << ">---------------------------------" << endl;
cerr << "Error: void Agent::newAgent(void),\n"
<< "there is no Scheduler !!" << endl;
cerr << "Stop..." << endl;
cerr << "<---------------------------------" << endl;
exit(1);
}
_baseClass = _class;
_class = getClassName(); // Voir DEFCLASS
if (_baseClass!=_class) _theAgentsSched->decNextInstanceNumber(_baseClass);
_theAgentsSched->removeInstance(this,_agentsClasses);
vector<string>::iterator iter;
for(iter = _agentsClasses.begin(); iter != _agentsClasses.end(); iter++)
{
_theAgentsSched->addNewInstance(This,*iter);
This->_agentsClasses.push_back(*iter);
}
/////////// Ou (pour conserver l'ordre dans This->_agentsClasses) ////
// {
// This->newAgent();
//
// // Mise a jour de This->_agentsClasses
//
// This->_agentsClasses.pop_back(); // il faudra remettre _class
//
// size_t agentsClassesSize=_agentsClasses.size();
// for(size_t i=0;i<agentsClassesSize;i++)
// {
// This->_agentsClasses.push_back(_agentsClasses[i]);
// }
//
// This->_agentsClasses.push_back(_class); // on remet _class
// }
/////////////////////////////////////////////////////////////////////
_name = ""; // _name = This->_name; // Mise a jour du nom
_baseClass = ""; // _baseClass = _baseClass; // On laisse comme c'est
_class = ""; // _class = getClassName(); // Voir DEFCLASS
_agentsClasses.clear(); // _agentsClasses = This->_agentsClasses;
// Indique que l'Agent ("mauvaise" branche de l'heritage
_deadAgent = true; // multiple) n'est plus a considerer lors d'un nouvel
// appel a newAgent
}
}
//--
void Agent::suspend(void)
{
_isSuspended = true;
}
//--
void Agent::restart(void)
{
_isSuspended = false;
}
//--
bool Agent::isSuspended(void) const
{
return _isSuspended;
}
/////////////////////////////////////////////////////////////////////////
// Pour changer de methode appelee par l'ordonnanceur...
// Pour programmeurs avertis, voir exemple :
// Exemples/ExemplesPourProgrammeursAvertis/Exemple_setLiveMethod
// --
// Dans setLiveMethod, si newLiveMethod est NULL alors c'est la methode
// live qui sera appelee par l'ordonnanceur...
// C'est le comportement par defaut..!
//
liveMethodType Agent::getLiveMethod(void)
{
return _liveMethod;
}
void Agent::setLiveMethod(liveMethodType newLiveMethod)
{
_liveMethod = newLiveMethod;
}
//
/////////////////////////////////////////////////////////////////////////
//--
bool operator==(const Agent& anAgent1, const Agent& anAgent2)
{
return anAgent1.isEqualTo(anAgent2);
}
//--
bool operator!=(const Agent& anAgent1, const Agent& anAgent2)
{
return !(anAgent1==anAgent2);
}
//--
string Agent::getClass(void) const
{
return _class;
}
//--
bool Agent::isA(string aClass) const
{
// Rappel: faire un find si autre chose que vector (set,...)
vector<string>::const_iterator iter;
for(iter = _agentsClasses.begin(); iter != _agentsClasses.end(); iter++)
{
if (*iter==aClass) return true;
}
return false;
}
//--
string Agent::getName(void) const
{
return _name;
}
//--
void Agent::setName(unsigned long instanceNumber)
{
ostringstream unsignedlongToString; unsignedlongToString << instanceNumber;
_name = getClass()+"."+unsignedlongToString.str();
}
//--
unsigned long Agent::getSuffix(void) const
{
string theName = getName();
const char *name = theName.c_str();
const char *suffix = strrchr(name,'.');
if (suffix==NULL) return 0;
unsigned long instanceNumber=0;
sscanf(suffix+1,"%lu",&instanceNumber); // +1 pour passer le .
return instanceNumber;
}
//--
ostream& operator<<(ostream& os,const Agent& anAgent)
{
anAgent.display(os);
return os;
}
void Agent::display(ostream& os) const
{
if (!_deadAgent)
{
os << _name << " : " << getClass() << endl;
os << "Nombre de messages en attente :" << getNbMessages() << endl;
vector<string>::const_iterator iter;
if (_agentsClasses.size()!=0)
{
os << _name << " est un : ";
for(iter = _agentsClasses.begin(); iter!= _agentsClasses.end(); iter++)
{
if (iter!=_agentsClasses.begin())
{
for(size_t n=0; n<_name.length();n++) os << ' ';
os << " ";
}
os << *iter << endl;
}
}
}
}
//--
bool Agent::isEqualTo(const Agent& anAgent) const
{
(void)anAgent; // Pour eviter un warning
#if 1 // A voir ..! , actuellement deux agents sont tjs egaux
return true; // Deux agents sont tjs egaux !!!!!
#else // OU
if (_name != anAgent._name) return false; // resultat de _name==anAgent._name
if (_liveMethod != anAgent._liveMethod) return false;
return true;
#endif
}
/////////////////////////////////////////////////////////////////////////////
/// Gestion mailBox
/////////////////////////////////////////////////////////////////////////////
//***********************************************
// map<string,size_t> _nbMessagesMap; // Pour chaque classe, le nb de messages
// void _addMessage(Message* message); // trois methodes pour connaitre le
// void _removeMessage(Message* message); // nb de messages d'un type
// size_t _nbMessages(string aClass) const; // particulier presents ds _mailBox
void Agent::_addMessage(Message* message)
{
if (message==NULL) return;
vector<string>& v = message->_messagesClasses;
vector<string>::iterator iterVect;
for(iterVect = v.begin(); iterVect != v.end(); iterVect++)
{
string aClass = *iterVect;
map<string,size_t>::iterator iter=_nbMessagesMap.find(aClass);
if (iter!=_nbMessagesMap.end()) ++(*iter).second; // ++ si deja present
else _nbMessagesMap[aClass]=1; // 1 si 1ere fois
}
}
void Agent::_removeMessage(Message* message)
{
if (message==NULL) return;
vector<string>& v = message->_messagesClasses;
vector<string>::iterator iterVect;
for(iterVect = v.begin(); iterVect != v.end(); iterVect++)
{
string aClass = *iterVect;
map<string,size_t>::iterator iter=_nbMessagesMap.find(aClass);
if (iter!=_nbMessagesMap.end()) --(*iter).second; // -- si deja present
else { // si absent : warning!!
cerr << "Warning Agent::removeMessage" << endl;
_nbMessagesMap[aClass]=0;
}
}
}
size_t Agent::_hmMessages(string aClass) const // how many messages
{
map<string,size_t>::const_iterator iter=_nbMessagesMap.find(aClass);
if (iter!=_nbMessagesMap.end()) return (*iter).second;
else return 0;
}
//***********************************************
#define USE_nbMessagesMap 1
//--
void Agent::putInMailBox(Message* message) // Private !... utilise dans la
{ // classe amie Message
if (message==NULL) return;
bool alreadyInMailBox=false;
// On regarde les differents cas pour voir si on ne peut pas simplement
// ajouter a la fin
// Sans priorite c'est simplement:
// _mailBox.push_back(message);
// _nbMessages++;
// #if USE_nbMessagesMap
// _addMessage(message);
// #endif
if (_mailBox.empty()) { _mailBox.push_back(message); alreadyInMailBox=true; }
if (!alreadyInMailBox)
{
list<Message*>::reverse_iterator it=_mailBox.rbegin();
if (message->_priority <= (*it)->_priority) { _mailBox.push_back(message);
alreadyInMailBox=true;
}
}
if (!alreadyInMailBox)
{
list<Message*>::iterator it;
for(it=_mailBox.begin();it!=_mailBox.end();it++)
{
if (message->_priority > (*it)->_priority) break;
}
_mailBox.insert(it,message);
}
_nbMessages++;
#if USE_nbMessagesMap
_addMessage(message);
#endif
}
//-----------
size_t Agent::_getNbMessages(void) const // Classe Message uniquement
{
if (_mailBox.empty()) return 0;
return _nbMessages; // _mailBox.size();
}
//--
size_t Agent::getNbMessages(string aClass) const
{
if (aClass=="Message") return _getNbMessages();
if (_mailBox.empty()) return 0;
#if USE_nbMessagesMap
//
return _hmMessages(aClass); // How many message
//
#else
//
size_t nb=0;
list<Message*>::const_iterator it;
for(it=_mailBox.begin();it!=_mailBox.end();it++)
{
if ((*it)->isA(aClass)) nb++;
}
return nb;
//
#endif
}
//-----------
//-----------
Message* Agent::_getNextMessage(void) // Classe Message uniquement
{
Message* newMessage = NULL;
if (!_mailBox.empty()) {
newMessage = _mailBox.front();
_mailBox.pop_front();
_nbMessages--;
}
#if USE_nbMessagesMap
_removeMessage(newMessage);
#endif
return newMessage;
}
//--
Message* Agent::getNextMessage(string aClass)
{
if (aClass=="Message") return _getNextMessage();
Message* newMessage = NULL;
list<Message*>::iterator it;
for(it=_mailBox.begin();it!=_mailBox.end();it++)
{
if ((*it)->isA(aClass)) { newMessage = *it;
_mailBox.erase(it);
_nbMessages--;
break;
}
}
#if USE_nbMessagesMap
_removeMessage(newMessage);
#endif
return newMessage;
}
//-----------
//-----------
Message* Agent::_getOneMessage(void) // Classe Message uniquement
{
Message* newMessage = NULL;
size_t nb = _getNbMessages();
if (nb==0) return newMessage; // NULL
size_t rang = randomMinMax(0,nb-1);
list<Message*>::iterator it=_mailBox.begin();
#if 1
for(size_t i=0;i<rang;i++) it++;
#else
it = it + rang;
#endif
newMessage = *it;
_mailBox.erase(it);
_nbMessages--;
#if USE_nbMessagesMap
_removeMessage(newMessage);
#endif
return newMessage;
}
//--
// Retourne un (aleatoirement) des Messages
// => Besoin de connaitre le nombre de messages d'une classe particuilere
Message* Agent::getOneMessage(string aClass)
{
if (aClass=="Message") return _getOneMessage();
Message* newMessage = NULL;
size_t nb = getNbMessages(aClass);
if (nb==0) return newMessage; // NULL
size_t rang = randomMinMax(0,nb-1);
// Chercher le message du bon type (aClass) se trouvant
// a la bonne position (rang)
list<Message*>::iterator it;
size_t pos=0;
for(it=_mailBox.begin();it!=_mailBox.end();it++)
{
if ((*it)->isA(aClass))
{
if (pos==rang) {
newMessage = *it;
_mailBox.erase(it);
_nbMessages--;
break;
}
else pos++;
}
}
#if USE_nbMessagesMap
_removeMessage(newMessage);
#endif
return newMessage;
}
//--
//-----------
//-- Et pourquoi pas :
size_t Agent::_getNbMessagesFrom(Agent* src) const // Classe Message uniquement
{
size_t nb=0;
list<Message*>::const_iterator it;
for(it=_mailBox.begin();it!=_mailBox.end();it++)
{
if ((*it)->getEmitter()==src) nb++;
}
return nb;
}
//--
size_t Agent::getNbMessagesFrom(Agent* src, string aClass) const
{
if (aClass=="Message") return _getNbMessagesFrom(src);
size_t nb=0;
list<Message*>::const_iterator it;
for(it=_mailBox.begin();it!=_mailBox.end();it++)
{
if ((*it)->isA(aClass) && (*it)->getEmitter()==src) nb++;
}
return nb;
}
//-----------
//--
//--
//-----------
//-- Et pourquoi pas aussi:
Message* Agent::_getNextMessageFrom(Agent* src) // Classe Message uniquement
{
Message* newMessage = NULL;
list<Message*>::iterator it;
for(it=_mailBox.begin();it!=_mailBox.end();it++)
{
if ((*it)->getEmitter()==src) { newMessage = *it;
_mailBox.erase(it);
_nbMessages--;
break;
}
}
#if USE_nbMessagesMap
_removeMessage(newMessage);
#endif
return newMessage;
}
//--
Message* Agent::getNextMessageFrom(Agent* src, string aClass)
{
if (aClass=="Message") return _getNextMessageFrom(src);
Message* newMessage = NULL;
list<Message*>::iterator it;
for(it=_mailBox.begin();it!=_mailBox.end();it++)
{
if ((*it)->isA(aClass) && (*it)->getEmitter()==src) { newMessage = *it;
_mailBox.erase(it);
_nbMessages--;
break;
}
}
#if USE_nbMessagesMap
_removeMessage(newMessage);
#endif
return newMessage;
}
//-----------
//--
//--
//-----------
//-- Et pourquoi pas aussi:
Message* Agent::_getOneMessageFrom(Agent* src) // Classe Message uniquement
{
Message* newMessage = NULL;
size_t nb = _getNbMessagesFrom(src);
if (nb==0) return newMessage; // NULL
size_t rang = randomMinMax(0,nb-1);
// Chercher le message (Message) avec le bon emetteur se trouvant
// a la bonne position (rang)
list<Message*>::iterator it;
size_t pos=0;
for(it=_mailBox.begin();it!=_mailBox.end();it++)
{
if ((*it)->getEmitter()==src)
{
if (pos==rang) {
newMessage = *it;
_mailBox.erase(it);
_nbMessages--;
break;
}
else pos++;
}
}
#if USE_nbMessagesMap
_removeMessage(newMessage);
#endif
return newMessage;
}
//--
Message* Agent::getOneMessageFrom(Agent* src,string aClass)
{
if (aClass=="Message") return _getOneMessageFrom(src);
Message* newMessage = NULL;
size_t nb = getNbMessagesFrom(src,aClass);
if (nb==0) return newMessage; // NULL
size_t rang = randomMinMax(0,nb-1);
// Chercher le message du bon type (aClass) avec le bon emetteur se trouvant
// a la bonne position (rang)
list<Message*>::iterator it;
size_t pos=0;
for(it=_mailBox.begin();it!=_mailBox.end();it++)
{
if ((*it)->isA(aClass) && (*it)->getEmitter()==src)
{
if (pos==rang) {
newMessage = *it;
_mailBox.erase(it);
_nbMessages--;
break;
}
else pos++;
}
}
#if USE_nbMessagesMap
_removeMessage(newMessage);
#endif
return newMessage;
}
//-----------
//--
//--
void Agent::clearMessageBox(void)
{
Message *m;
m = getNextMessage();
while (m!=NULL)
{
delete m;
m = getNextMessage();
}
}
/////////////////////////////////////////////////////////////////////////////
/// FIN Gestion mailBox
/////////////////////////////////////////////////////////////////////////////
//--
void Agent::setSensitivity(string aClass,bool yesNo)
{
if (yesNo)
{
// On memorise que l'Agent est sensible
_sensitivity.insert(aClass);
}
else
{
// On indique que l'Agent n'est plus sensible
_sensitivity.erase(aClass);
}
Message::setSensitivity(aClass,this,yesNo);
}
//--
size_t Agent::sendMessageTo(Message& aM,Agent *dest) const
{
if (!exist(dest)) return 0;
aM.setEmitter((Agent*)this);
return aM.sendTo(dest);
}
//--
void Agent::broadcastMessage(Message& aM) const
{
aM.setEmitter((Agent*)this);
aM.broadcast();
}
//--
void Agent::_copy(const Agent& anAgent)
{
/*
Recopie la boite aux lettres en prenant soin de
dupliquer les messages pointe's
+ _nbMessagesMap
+ gestion de _sensitivity
+ _isSuspended
+ _liveMethod
*/
#if 1
list<Message*>::const_iterator itDeque;
for(itDeque=anAgent._mailBox.begin();
itDeque!=anAgent._mailBox.end();
itDeque++)
{
Message* m = *itDeque;
Message *newMessage = (Message*)m->virtualCopy();
putInMailBox(newMessage);
}
#else
Agent& pasBeau=(Agent&)anAgent;
size_t nbMess= anAgent.getNbMessages();
for(size_t i = 0; i < nbMess; i++)
{
// Si on ne peut pas parcourir la boite directement (avec begin,end,[],...)
// => On enleve le message et on le remet tout de suite a la fin
Message *m = pasBeau.getNextMessage();
pasBeau.putInMailBox(m);
Message *newMessage = (Message*)m->virtualCopy();
putInMailBox(newMessage);
}
#endif
#if USE_nbMessagesMap
// _nbMessagesMap = anAgent._nbMessagesMap; // Copie de la map ...!
// En fait, ce n'est pas utile car on ajoute dans la boite avec
// putInMailBox... et donc on fait deja ce qu'il faut dans la map..!
#endif
set<string>::const_iterator itSet;
for(itSet = anAgent._sensitivity.begin();
itSet!= anAgent._sensitivity.end();
itSet++)
{
setSensitivity(*itSet,true);
}
_isSuspended = anAgent._isSuspended;
_liveMethod = anAgent._liveMethod;
}
//--
void Agent::_destroy(void)
{
/*
Destruction de la boite aux lettres en prenant soin de
detruire les messages pointe's
+ gestion de _sensitivity
*/
clearMessageBox();
set<string> sensitivity = _sensitivity;
set<string>::iterator it;
for(it = sensitivity.begin(); it != sensitivity.end(); it++)
{
setSensitivity(*it,false);
}
_liveMethod = NULL;
}
|
14336664b8df5685b5290836b998430bf1273a0d
|
3d35cee4d712b9070ffb29c6380808adc6673b76
|
/Questions/3.cpp
|
ea66a745d067b8cac6ed8e9a24cadf77e0a1327d
|
[] |
no_license
|
Rittik-kumar/C-Plus-Plus
|
50e7756d9679bb2952a593dde3264e19bf0251d4
|
1a19a36cc240e001bdd92930b40c2930bb56265d
|
refs/heads/main
| 2023-05-27T13:08:05.825278
| 2021-06-10T15:26:13
| 2021-06-10T15:26:13
| 371,876,226
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 243
|
cpp
|
3.cpp
|
/*
Jump Statement
Input:
1
2
88
42
99
Output:
1
2
88
*/
#include<bits/stdc++.h>
using namespace std;
int main()
{
while(true)
{
int x;
cin>> x;
if(x==42)
break;
cout<< x << endl;
}
}
|
0d98ceedff5b9d641316f5fb49fd5e71e894149c
|
c4790552abc608f491b7ac2a0b6dcd5826a5bd7c
|
/500D.cpp
|
b4cef7628b81f4928aa96243a62480167c35a5c4
|
[] |
no_license
|
jeffry1829/ojcode
|
bd03df14360e5c00e6463c3621de0cfeef88bb11
|
18a6fa3aa59e0d9c274f44f7dea060f70c91cbe8
|
refs/heads/master
| 2023-02-27T00:27:04.856978
| 2021-02-04T09:20:58
| 2021-02-04T09:20:58
| 286,199,256
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 3,615
|
cpp
|
500D.cpp
|
//#pragma GCC optimize(1)
//#pragma GCC optimize(2)
#pragma GCC optimize(3)
#pragma GCC optimize("Ofast")
#pragma GCC optimize("inline")
#pragma GCC optimize("-fgcse")
#pragma GCC optimize("-fgcse-lm")
#pragma GCC optimize("-fipa-sra")
#pragma GCC optimize("-ftree-pre")
#pragma GCC optimize("-ftree-vrp")
#pragma GCC optimize("-fpeephole2")
#pragma GCC optimize("-ffast-math")
#pragma GCC optimize("-fsched-spec")
#pragma GCC optimize("unroll-loops")
#pragma GCC optimize("-falign-jumps")
#pragma GCC optimize("-falign-loops")
#pragma GCC optimize("-falign-labels")
#pragma GCC optimize("-fdevirtualize")
#pragma GCC optimize("-fcaller-saves")
#pragma GCC optimize("-fcrossjumping")
#pragma GCC optimize("-fthread-jumps")
#pragma GCC optimize("-funroll-loops")
#pragma GCC optimize("-freorder-blocks")
#pragma GCC optimize("-fschedule-insns")
#pragma GCC optimize("inline-functions")
#pragma GCC optimize("-ftree-tail-merge")
#pragma GCC optimize("-fschedule-insns2")
#pragma GCC optimize("-fstrict-aliasing")
#pragma GCC optimize("-falign-functions")
#pragma GCC optimize("-fcse-follow-jumps")
#pragma GCC optimize("-fsched-interblock")
#pragma GCC optimize("-fpartial-inlining")
#pragma GCC optimize("no-stack-protector")
#pragma GCC optimize("-freorder-functions")
#pragma GCC optimize("-findirect-inlining")
#pragma GCC optimize("-fhoist-adjacent-loads")
#pragma GCC optimize("-frerun-cse-after-loop")
#pragma GCC optimize("inline-small-functions")
#pragma GCC optimize("-finline-small-functions")
#pragma GCC optimize("-ftree-switch-conversion")
#pragma GCC optimize("-foptimize-sibling-calls")
#pragma GCC optimize("-fexpensive-optimizations")
#pragma GCC optimize("inline-functions-called-once")
#pragma GCC optimize("-fdelete-null-pointer-checks")
#pragma comment(linker, "/STACK:1024000000,1024000000")
#include <bits/stdc++.h>
using namespace std;
//#define int long long
#define rep(i,a,n) for(int i=a;i<n;i++)
#define per(i,a,n) for(int i=n-1;i>=a;i--)
#define pb push_back
//#define mp make_pair
#define all(x) (x).begin(),(x).end()
#define fi first
#define se second
#define SZ(x) ((int)(x).size())
#define min(a,b) (((a)<(b))?(a):(b))
#define max(a,b) (((a)>(b))?(a):(b))
#define abs(x) (((x)<0)?(-(x)):(x))
typedef vector<int> VI;
typedef long long ll;
typedef pair<int,int> PII;
typedef double db;
mt19937 mrand(random_device{}());
const ll mod=1000000007;
int rnd(int x){return mrand()%x;}
ll powmod(ll a,ll b){ll res=1;a%=mod;assert(b>=0);for(;b;b>>=1){if(b&1)res=res*a%mod;a=a*a%mod;}return res;}
ll gcd(ll a, ll b){return b?gcd(b,a%b):a;}
#define y1 ojsapogjahg
#define prev ojaposjdas
#define rank oiajgpowsdjg
#define left aijhgpiaejhgp
//#define end aononcncnccc
inline int pmod(int x, int d){int m = x%d;return m+((m>>31)&d);}
//head
const int _n=1e5+10;
int t,n,a,b,l,q,r,w,fa[_n],cnt[_n],dep[_n];
ll sum;
vector<PII> G[_n];
struct E{int u,v,w;} e[_n];
ll C(ll x){if(x<2ll)return 0;return x*(x-1)/2ll;}
void dfs(int v,int faa,int d){
fa[v]=faa,dep[v]=d,cnt[v]=1;
rep(i,0,SZ(G[v]))if(G[v][i].fi!=faa)
dfs(G[v][i].fi,v,d+1),cnt[v]+=cnt[G[v][i].fi];
}
main(void) {ios_base::sync_with_stdio(0);cin.tie(0);cout.tie(0);
cin>>n;rep(i,1,n){cin>>a>>b>>l;a--,b--;G[a].pb({b,l}),G[b].pb({a,l});e[i]={a,b,l};}
dfs(0,-1,0);rep(i,1,n){
int u=e[i].u,v=e[i].v,w=e[i].w;
if(dep[u]>dep[v])swap(u,v);
sum+=1ll*cnt[v]*(n-cnt[v])*w;
}
cin>>q;while(q--){
cin>>r>>w;int u=e[r].u,v=e[r].v;
if(dep[u]>dep[v])swap(u,v);
sum-=1ll*cnt[v]*(n-cnt[v])*e[r].w;
sum+=1ll*cnt[v]*(n-cnt[v])*w;
cout<<setprecision(20)<<3.0*sum/(1.0*C(n))<<'\n';
e[r].w=w;
}
return 0;
}
|
b6935c6048c25aeeacfb1ad7bb6d4703bea5d10e
|
e29fe554f01ed7b3476c627235c1c776259aa5ad
|
/src/Article/Article.h
|
fbc72cd140daa22e05793ca9da5e7b1f22b78753
|
[] |
no_license
|
fez2000/commerce
|
57207e581d8c2613ec2d59476e6b91e9d6178bc7
|
8e63a42b050d29c24f7849a1d6ef3205df5497bd
|
refs/heads/master
| 2020-05-20T04:59:13.048400
| 2019-11-05T16:50:12
| 2019-11-05T16:50:12
| 185,393,980
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,193
|
h
|
Article.h
|
#ifndef ARTICLE_H_INCLUDE
#define ARTICLE_H_INCLUDE
#include <fstream>
#include <string>
#include "../fonctions/fonctions.h"
namespace Article
{
/*
@brief classe de base d'un atricle permettant d'effectuer des operations elementaire sur un atricle
@proprietes:
-refernce: identifiant d'un article
-libelle: nom de l'article
-prix: prix d'un article
-quantite: quantite de l'article disponible
-seuil: la quatite a partir de laquelle un article est critique
@methodes:
-fixer_prix: pour mettre a jour le prix d'un atricle
-fixer_quantite: pour mettre a jour la quantite d'atricle disponible
-ajouter_quantite: pour augmenter une quantite d'atricle
-a_ravitailler: teste la quantite d'article disponible est en dessous de seuil
-tester_libelle: permet de comparer le libelle avec une chaine retourne 0 si egale
-tester_quantite: permet de comparer deux quantites
*/
class Base
{
private:
typeId reference;
std::string libelle;
double prix;
unsigned long quantite;
unsigned long seuil;
public:
Base();
Base(typeId,std::string,unsigned long,unsigned long,unsigned long);
~Base();
std::string get_libelle();
Base* fixer_prix(unsigned long);
Base* fixer_quantite(unsigned long);
Base* ajouter_quantite(long);
bool a_ravitailler(void);
bool tester_reference(typeId);
int tester_libelle(const char *);
typeId get_reference(void);
double get_prix(void);
unsigned long get_quantite(void);
unsigned long get_seuil(void);
long tester_quantite(unsigned long);
friend int operator== (Base,Base);
friend int operator< (Base,Base);
friend int operator<= (Base,Base);
friend int operator> (Base,Base);
Base & operator= (const Base &);
friend std::ostream& operator<<(std::ostream &os, const Base &b);
friend std::istream& operator>>(std::istream &is, Base &b);
};
} // atricle
#endif
|
b123dda2e4e6d98d095d1d388aeac45568898338
|
2ee7bb14ebe14cceba4de7ad7d5b2797682b125f
|
/TcpSession.cpp
|
163b2d3a10417fe1fcc640a76297781f13a29fff
|
[] |
no_license
|
LaiDevin/iocp
|
90ed0ebdd1c87b1d49b59ca82fcb15642fd67360
|
4098d1dd5b6c3cbdf49589676997df9e95c418cf
|
refs/heads/master
| 2020-03-18T09:06:27.933252
| 2018-05-22T22:14:35
| 2018-05-22T22:14:35
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,925
|
cpp
|
TcpSession.cpp
|
#include "TcpSession.h"
#include "Socket.h"
#include "Global.h"
#include "TcpListener.h"
#include <MSWSock.h>
#include "IoCallbackAccept.h"
#include "IoCallbackConnect.h"
#include "IoCallbackRecv.h"
#include "IoCallbackReuse.h"
#include "IoCallbackSend.h"
TcpSession::TcpSession()
{
_pSocket = new Socket();
_pAcceptCallback = new IoCallbackAccept();
_pConnectCallback = new IoCallbackConnect();
_pRecvCallback = new IoCallbackRecv(1024);
_pReuseCallback = new IoCallbackReuse();
_pSendCallback = new IoCallbackSend();
}
TcpSession::~TcpSession()
{
SafeDelete(_pSocket);
SafeDelete(_pAcceptCallback);
SafeDelete(_pConnectCallback);
SafeDelete(_pRecvCallback);
SafeDelete(_pReuseCallback);
SafeDelete(_pSendCallback);
}
HANDLE TcpSession::GetHandle() const
{
return _pSocket->GetHandle();
}
bool TcpSession::Accept()
{
SecureZeroMemory(&_localSockaddr, sizeof(_localSockaddr));
SecureZeroMemory(&_remoteSockaddr, sizeof(_remoteSockaddr));
return _pAcceptCallback->Post();
}
bool TcpSession::Accept(const IoCallbackFn&& fn, shared_ptr<TcpListener> listenerPtr)
{
if(!listenerPtr) return false;
_pAcceptCallback->Bind(shared_from_this(), move(fn), listenerPtr);
return Accept();
}
void TcpSession::Close()
{
_pSocket->Close();
}
bool TcpSession::Create()
{
if(!_pSocket->Create(SOCK_STREAM, IPPROTO_TCP))
return false;
if(!_pSocket->SetNonblock(true))
return false;
return true;
}
bool TcpSession::Recv(const IoCallbackFnRecv&& fn)
{
_pRecvCallback->Bind(shared_from_this(), move(fn));
return _pRecvCallback->Post();
}
bool TcpSession::Reuse(const IoCallbackFn&& fn)
{
_pReuseCallback->Bind(shared_from_this(), move(fn));
return _pReuseCallback->Post();
}
bool TcpSession::Send(const IoCallbackFnSend&& fn, const WSABUF& buf)
{
// TODO: if the queue is not empty enqueue packet there.
_pSendCallback->Bind(shared_from_this(), move(fn), buf);
return _pSendCallback->Post();
}
|
50216a551b7e32e488d84c0da489079b0c4c655a
|
53bbe87ff7f94fd0a87f0b5ea12f4babffe4bbd7
|
/02-classes-constructors-destructors/3-static/old/points.bounds.cpp
|
172291ba96a8bf76c5869b84a31877d2cc76f9dc
|
[
"MIT"
] |
permissive
|
sagiehod/cpp-5781
|
961df881f1dcbe65c9a4e0ff9866f5decd6dac1f
|
615ba07e0841522df74384f380172557f5e305a7
|
refs/heads/master
| 2023-06-02T18:54:41.921574
| 2021-06-13T18:48:25
| 2021-06-13T18:48:25
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,279
|
cpp
|
points.bounds.cpp
|
/**
* Demonstrates static members.
* Creates a class "point" with static members for the upper and lower bounds.
*/
#include <iostream>
#include <stdexcept>
using namespace std;
class Point {
int x;
int y;
public:
// A static const can be initialized inline:
static const int MAXX=1366;
// A static non-const must be initialized out-of-line:
static int MAXY;
void setX(int newX) {
if (newX>MAXX)
throw out_of_range("New x is too large! The maximum is "+std::to_string(MAXX));
x = newX;
}
void setY(int newY) {
if (newY>MAXY)
throw out_of_range("New y is too large! The maximum is "+std::to_string(MAXY));
y = newY;
}
string to_string() {
return "("+std::to_string(x)+","+std::to_string(y)+")";
}
static void showMax() {
cout << MAXX << "," << MAXY << endl;
}
};
int Point::MAXY = 766;
int main() {
Point p1;
cout << "p1 = " << p1.to_string() << endl;
Point p2;
p2.setX(10);
p2.setY(20);
cout << "p2 = " << p2.to_string() << endl;
cout << "Maximum values: " << endl;
cout << Point::MAXX << "," << Point::MAXY << endl;
Point::showMax();
//p2.setX(2000); // exception
return 0;
}
|
46b274e3c05037023b064e1b7d8998629ea811d0
|
3ac5c3c490e6a9ae2968b1d78d825b048b48c8ed
|
/spotyXLogic/3-infra/repository/UserSpotifyDataRepository.h
|
755231ead6c03851b180cd9a00c2811a357d2530
|
[] |
no_license
|
geronimo-lisboa/qt-spotify
|
774a667be066ddf90c5c82829c905ec409fd1b19
|
04097ef0e5f42e75ecb8206558cdfcd87e564be9
|
refs/heads/master
| 2020-03-30T17:25:24.324683
| 2018-10-08T17:07:32
| 2018-10-08T17:07:32
| 151,454,935
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 923
|
h
|
UserSpotifyDataRepository.h
|
#ifndef UserSpotifyDataRepository_h
#define UserSpotifyDataRepository_h
#include <vector>
#include <memory>
//forward declarations
class QSqlDatabase;
namespace model
{
class UserSpotifyData;
class User;
}
using namespace std;
namespace infra
{
class UserSpotifyDataRepository
{
private:
QSqlDatabase& database;
public:
typedef vector<shared_ptr<model::UserSpotifyData>> ListOfSpotifyData;
UserSpotifyDataRepository(QSqlDatabase& db);
//Todos os métodos dessa classe são stateless
void init() const;
void addSpotifyData(std::shared_ptr<model::UserSpotifyData> d) const;
void updateSpotifyData(std::shared_ptr<model::UserSpotifyData> d) const;
shared_ptr<model::UserSpotifyData> getSpotifyData(model::User& usu);
shared_ptr<model::UserSpotifyData> getSpotifyData(int id);
void purgeSpotifyData()const;
};
}
#endif
|
e61a65dc60dbebc6351fc80abd9abcbd9be49d19
|
4b33c4d41f4eaff87674301f7d3a22c5b80da63b
|
/libs/libciaran/ciaran.hpp
|
e44097a9de468faf4217bc4a2fd052873f790b72
|
[] |
no_license
|
CUA-BatDrone/Bat-Drone-Software
|
63f722c7de0958151f2d31fb5bebcb8bf6a633b7
|
4ceef0c93baee6eafa8e8920ae23658743e57e78
|
refs/heads/master
| 2021-09-13T11:48:18.947468
| 2018-04-29T10:35:21
| 2018-04-29T10:35:21
| 106,051,655
| 2
| 2
| null | 2018-04-05T03:44:00
| 2017-10-06T21:26:33
|
C
|
UTF-8
|
C++
| false
| false
| 206
|
hpp
|
ciaran.hpp
|
#ifndef CIARAN_HPP
#define CIARAN_HPP
#define rows 60
#define cols 80
#include <stdint.h>
extern uint16_t centerX;
extern uint16_t centerY;
int detectBlob(uint16_t arr[rows][cols]);
#endif
|
50f5ff4a6c991289ff4c55deb2fd04b32f8bdf58
|
82091fc56c850906f3a36e8cb20fbb69c9b50e96
|
/ucc/BinTreeNode.cpp
|
4b1b33de1ebd40cbf5b77469f7c41c4abc59a3b2
|
[
"MIT"
] |
permissive
|
inbei/libutl
|
97a57b865b4ab2331d66545fa2bb48ddf928ac2b
|
e55c2af091ba1101a1d0608db2830e279ec95d16
|
refs/heads/master
| 2023-07-22T15:35:51.113701
| 2021-08-26T09:28:22
| 2021-08-26T09:28:22
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 8,284
|
cpp
|
BinTreeNode.cpp
|
#include <libutl/libutl.h>
#include <libutl/BinTreeNode.h>
#include <libutl/Queue.h>
////////////////////////////////////////////////////////////////////////////////////////////////////
UTL_NS_BEGIN;
////////////////////////////////////////////////////////////////////////////////////////////////////
void
BinTreeNode::dump(Stream& os, uint_t level)
{
// terminate on a leaf node
if (isLeaf())
return;
// write our object
for (uint_t i = 0; i < 2 * level; i++)
{
os << ' ';
}
os << *_object << endl;
// dump children
_left->dump(os, level + 1);
_right->dump(os, level + 1);
}
////////////////////////////////////////////////////////////////////////////////////////////////////
BinTreeNode*
BinTreeNode::leftMost()
{
// Just walk down the left side of the tree until we reach a leaf
BinTreeNode* res = this;
while (!res->_left->isLeaf())
res = res->_left;
return res;
}
////////////////////////////////////////////////////////////////////////////////////////////////////
BinTreeNode*
BinTreeNode::next() const
{
BinTreeNode* res;
// if the right child is a leaf
if (_right->isLeaf())
{
// The right child is a leaf, so the successor is found by walking
// up the tree until we find a node that is a left child. That
// node's parent is the successor. If no such node is found, there
// is no successor.
res = const_cast_this;
// walk up the tree until we find a node that isn't a right child
while (res->isRightChild())
res = res->_parent;
// if the node is a left child, we've found the successor
if (res->isLeftChild())
{
res = res->_parent;
}
// else there is no successor
else
{
res = nullptr;
}
}
// else the successor is the smallest node in the right subtree
else
{
res = _right->leftMost();
}
return res;
}
////////////////////////////////////////////////////////////////////////////////////////////////////
BinTreeNode*
BinTreeNode::prev() const
{
BinTreeNode* res;
// if the left child is a leaf
if (_left->isLeaf())
{
// The left child is a leaf, so the predecessor is found by walking
// up the tree until we find a node that is a right child. That
// node's parent is the predecessor. If no such node is found, there
// is no predecessor.
res = const_cast_this;
// walk up the tree until we find a node that isn't a left child
while (res->isLeftChild())
res = res->_parent;
// if the node is a right child, we've found the predecessor
if (res->isRightChild())
{
res = res->_parent;
}
// else there is no predecessor
else
{
res = nullptr;
}
}
// else the predecessor is the largest node in the left subtree
else
{
res = _left->rightMost();
}
return res;
}
////////////////////////////////////////////////////////////////////////////////////////////////////
void
BinTreeNode::remove(BinTreeNode*& p_x, BinTreeNode*& p_y)
{
BinTreeNode* z = this;
BinTreeNode* x;
BinTreeNode* y;
// y is the node that will actually be removed
if ((z->left()->isLeaf()) || (z->right()->isLeaf()))
{
// simple case -- z has a NIL child
y = z;
}
else
{
// y is z's successor
y = z->next();
// swap y's contents with z's
y->swapWith(z);
// swap y,z pointers
BinTreeNode* tmp;
tmp = y;
y = z;
z = tmp;
}
// x is y's only child
if (y->left()->isLeaf())
{
x = y->right();
}
else
{
x = y->left();
}
// Remove y from the parent chain
x->_parent = y->_parent;
if (!y->isRoot())
{
if (y->isLeftChild())
{
y->parent()->_left = x;
}
else
{
y->parent()->_right = x;
}
}
p_x = x;
p_y = y;
}
////////////////////////////////////////////////////////////////////////////////////////////////////
BinTreeNode*
BinTreeNode::rightMost()
{
BinTreeNode* res = this;
while (!res->_right->isLeaf())
{
res = res->_right;
}
return res;
}
////////////////////////////////////////////////////////////////////////////////////////////////////
// note: this only handles the cases required by remove()
void
BinTreeNode::swapWith(BinTreeNode* rhs)
{
BinTreeNode* lhs = this;
BinTreeNode* tmp;
bool lhsIsLC = lhs->isLeftChild();
bool rhsIsLC = rhs->isLeftChild();
// lhs is child of rhs?
if (lhs->_parent == rhs)
{
lhs->_parent = rhs->_parent;
rhs->_parent = lhs;
// lhs must be right child of rhs
ASSERTD(!lhsIsLC);
tmp = lhs->_left;
lhs->_left = rhs->_left;
rhs->_left = tmp;
tmp = lhs->_right;
lhs->_right = rhs;
rhs->_right = tmp;
// re-set child links in parent of rhs
if (lhs->_parent != nullptr)
{
if (rhsIsLC)
lhs->_parent->_left = lhs;
else
lhs->_parent->_right = lhs;
}
}
else // simple case: no relationship between lhs, rhs
{
ASSERTD(rhs->_parent != lhs);
// swap parent links
tmp = lhs->_parent;
lhs->_parent = rhs->_parent;
rhs->_parent = tmp;
// swap child links
tmp = lhs->_left;
lhs->_left = rhs->_left;
rhs->_left = tmp;
tmp = lhs->_right;
lhs->_right = rhs->_right;
rhs->_right = tmp;
// re-set child links in parents
if (lhs->_parent != nullptr)
{
if (rhsIsLC)
lhs->_parent->_left = lhs;
else
lhs->_parent->_right = lhs;
}
if (rhs->_parent != nullptr)
{
if (lhsIsLC)
rhs->_parent->_left = rhs;
else
rhs->_parent->_right = rhs;
}
}
// re-set parent links in children
lhs->_left->_parent = lhs;
lhs->_right->_parent = lhs;
rhs->_left->_parent = rhs;
rhs->_right->_parent = rhs;
}
////////////////////////////////////////////////////////////////////////////////////////////////////
void
BinTreeNode::rotateLeft()
{
BinTreeNode* x = this;
BinTreeNode* y = x->_right;
// y's left becomes x's right
x->_right = y->_left;
y->_left->_parent = x;
// x's parent becomes y's parent
y->_parent = x->_parent;
if (x->_parent != nullptr)
{
if (x == x->_parent->_left)
{
x->_parent->_left = y;
}
else
{
x->_parent->_right = y;
}
}
// x is now y's left
y->_left = x;
x->_parent = y;
}
////////////////////////////////////////////////////////////////////////////////////////////////////
void
BinTreeNode::rotateRight()
{
BinTreeNode* x = this;
BinTreeNode* y = x->_left;
// y's right becomes x's left
x->_left = y->_right;
y->_right->_parent = x;
// x's parent becomes y's parent
y->_parent = x->_parent;
if (x->_parent != nullptr)
{
if (x == x->_parent->_right)
{
x->_parent->_right = y;
}
else
{
x->_parent->_left = y;
}
}
// x is now y's right
y->_right = x;
x->_parent = y;
}
////////////////////////////////////////////////////////////////////////////////////////////////////
BinTreeNode*
BinTreeNode::sibling() const
{
if (_parent == nullptr)
{
return nullptr;
}
else
{
return (this == _parent->_left) ? _parent->_right : _parent->_left;
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////
void
BinTreeNode::init(const Object* object)
{
_parent = _left = _right = nullptr;
_object = const_cast<Object*>(object);
}
////////////////////////////////////////////////////////////////////////////////////////////////////
UTL_NS_END;
|
9f9a3406bcee1bb3b5f7e02eb6721c1abdb3fb3a
|
87a600d36a5757969ead7e235c93e3530d72b43a
|
/abm_product/bak/app_guard/sysinfo_j.cpp
|
419e129598e05be3c37f2cfef2eef3cb68312cad
|
[] |
no_license
|
xkmld419/learning
|
3c3cad407d03bf693bcd863794cca7fb8a5df99a
|
128ffa1496c43c36b83f266522bd49b28184499f
|
refs/heads/master
| 2023-07-12T16:54:50.647834
| 2021-08-21T15:41:42
| 2021-08-21T15:41:42
| 45,075,836
| 1
| 0
| null | null | null | null |
GB18030
|
C++
| false
| false
| 3,318
|
cpp
|
sysinfo_j.cpp
|
/* Copyright (c) 2001-<2003> Wholewise, All rights Reserved */
/* #ident "@(#)sysinfo_j.c 1.0 2011/07/06 <AutoCreate>" */
#include "sysinfo.h"
Control *sysinfo_init()
{
Control *Ctl7,*Ctl9,*Ctl1,*Ctl2,*Ctl3,*Ctl4,*Ctl6,*Ctl12;
RECT rt; TFILE *pHead;
ReadFile("sysinfo.rc", (TFILE **)&pHead);
GetSiteInfo( pHead, 0, &rt);
Ctl7 = CtlInit(LABEL ,rt.iId,rt.iTop,rt.iLeft,rt.iWidth,rt.iHeight);
GetSiteInfo( pHead, 1, &rt);
Ctl9 = CtlInit(BOX ,rt.iId,rt.iTop,rt.iLeft,rt.iWidth,rt.iHeight);
GetSiteInfo( pHead, 2, &rt);
Ctl1 = CtlInit(BUTTON ,rt.iId,rt.iTop,rt.iLeft,rt.iWidth,rt.iHeight);
GetSiteInfo( pHead, 3, &rt);
Ctl2 = CtlInit(BUTTON ,rt.iId,rt.iTop,rt.iLeft,rt.iWidth,rt.iHeight);
GetSiteInfo( pHead, 4, &rt);
Ctl3 = CtlInit(BUTTON ,rt.iId,rt.iTop,rt.iLeft,rt.iWidth,rt.iHeight);
GetSiteInfo( pHead, 5, &rt);
Ctl4 = CtlInit(BUTTON ,rt.iId,rt.iTop,rt.iLeft,rt.iWidth,rt.iHeight);
GetSiteInfo( pHead, 6, &rt);
Ctl6 = CtlInit(LIST ,rt.iId,rt.iTop,rt.iLeft,rt.iWidth,rt.iHeight);
GetSiteInfo( pHead, 7, &rt);
Ctl12 = CtlInit(LABEL ,rt.iId,rt.iTop,rt.iLeft,rt.iWidth,rt.iHeight);
strcpy( Ctl7 ->sData , "当前位置: HSS监控>> 系统信息>>" );
strcpy( Ctl1 ->sData , "1.系统性能" );
strcpy( Ctl2 ->sData , "2.磁盘空间" );
strcpy( Ctl3 ->sData , "3.表空间" );
strcpy( Ctl4 ->sData , "q.退出" );
strcpy( Ctl12 ->sData , "系统信息:" );
Ctl1 ->pKeyPress = (KEYPRESS)&sysinfoCtl1Press;
Ctl2 ->pKeyPress = (KEYPRESS)&sysinfoCtl2Press;
Ctl3 ->pKeyPress = (KEYPRESS)&sysinfoCtl3Press;
Ctl4 ->pKeyPress = (KEYPRESS)&sysinfoCtl4Press;
Ctl6 ->pKeyPress = (KEYPRESS)&sysinfoCtl6Press;
Ctl1 ->pHotKeyPress = (KEYPRESS)&sysinfo_SysHotKeyPress;
Ctl2 ->pHotKeyPress = (KEYPRESS)&sysinfo_SysHotKeyPress;
Ctl3 ->pHotKeyPress = (KEYPRESS)&sysinfo_SysHotKeyPress;
Ctl4 ->pHotKeyPress = (KEYPRESS)&sysinfo_SysHotKeyPress;
Ctl6 ->pHotKeyPress = (KEYPRESS)&sysinfo_SysHotKeyPress;
Ctl1 ->iHotKey = '1' ;
Ctl2 ->iHotKey = '2' ;
Ctl3 ->iHotKey = '3' ;
Ctl4 ->iHotKey = 'q' ;
Ctl9 ->bFrame = 1 ;
Ctl6 ->bFrame = 1 ;
Ctl6 ->bSingle = 0 ;
CtlSetDir(Ctl7 , NULL, NULL, NULL, NULL, NULL, Ctl9);
CtlSetDir(Ctl9 , NULL, NULL, NULL, NULL, NULL, Ctl1);
CtlSetDir(Ctl1 , Ctl6, NULL, Ctl4, Ctl2, Ctl2, Ctl2);
CtlSetDir(Ctl2 , Ctl6, NULL, Ctl1, Ctl3, Ctl3, Ctl3);
CtlSetDir(Ctl3 , Ctl6, NULL, Ctl2, Ctl4, Ctl4, Ctl4);
CtlSetDir(Ctl4 , Ctl6, NULL, Ctl3, Ctl1, Ctl1, Ctl6);
CtlSetDir(Ctl6 , Ctl1, Ctl1, Ctl1, Ctl1, Ctl1, Ctl12);
CtlSetDir(Ctl12 , NULL, NULL, NULL, NULL, NULL, NULL);
FreeFileMem( pHead );
sysinfo_entry((Control *)Ctl7);
return ((Control *)Ctl7) ;
}
sysinfo::sysinfo()
{
m_pForm = (Control *) sysinfo_init ();
}
sysinfo::~sysinfo()
{
FormKill (m_pForm);
m_pForm = NULL;
}
int sysinfo::run()
{
if (FormRun (m_pForm) == FORM_KILL_OK)
m_pForm = NULL;
return FORM_KILL_OK;
}
|
4bea1367fafee366be3d3cc98c7386fb0eccff7b
|
7ec4ce13fe476404a1769d9958dc41bef48661bc
|
/数据结构/07022018/BST.h
|
9177ec17446a9f2a168c92965742187572b6cf41
|
[] |
no_license
|
meihao1203/learning
|
45679e1b0912b62f7a6ef1999fb2a374733f5926
|
dbef1a1b6ccb704c53b2439661d062eb69060a0d
|
refs/heads/master
| 2021-07-19T23:36:50.602595
| 2018-12-09T02:03:06
| 2018-12-09T02:03:06
| 113,955,622
| 11
| 4
| null | null | null | null |
GB18030
|
C++
| false
| false
| 741
|
h
|
BST.h
|
#ifndef __BST_H__
#define __BST_H__
#include<iostream>
using namespace std;
typedef struct Binary_Sort_Tree
{
int data;
struct Binary_Sort_Tree* lchild,*rchild;
}bstNode,*pBstNode;
void BST_Insert(pBstNode& root,int data); //二叉排序树中插入结点
bstNode* BST_Search(pBstNode root,int key); //二叉排序树中查找关键字key
int deleteNode(bstNode*& node); //删除节点node,形参为待删除节点的地址本身
int BST_Delete(pBstNode& root,int key); //二叉树删除关键字key //成功返回
/* 二叉搜索树的三种遍历 */
void preorderTraversal_BST(const pBstNode& root);
void inorderTraversal_BST(const pBstNode& root);
void postorderTraversal_BST(const pBstNode& root);
#endif
|
a70025dc49fd07f3bd06b0e90454f7b1cbee5dfd
|
f99b0f57bad6380dea4a866afbdb7ebc58ba7647
|
/XeniaAndRingroad.cpp
|
c1059872c7530194218980b5e2756244e948fb93
|
[] |
no_license
|
psluke2104/PopularProgrammingProblems
|
2a95ec5e3fc91284f49c65253638ff0b280689a9
|
24472c3bec176b7bd4a8312604c2bc6a10e0b260
|
refs/heads/master
| 2022-12-19T08:21:30.502430
| 2020-10-01T07:37:13
| 2020-10-01T07:37:13
| 271,739,027
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 385
|
cpp
|
XeniaAndRingroad.cpp
|
#include<iostream>
using namespace std;
int main(){
int n,m;
cin>>n>>m;
int arr[m+1];
arr[0] = 1;
for(int i=1 ; i<m+1 ; i++){
cin>>arr[i];
}
int count= 0;
for(int j=0;j<m;j++){
if(arr[j]<arr[j+1]){
count += arr[j+1]-arr[j];
}
else if(arr[j]>arr[j+1]){
count += n - arr[j]+arr[j+1];
}
else if(arr[j]==arr[j+1])
continue;
}
cout<<count;
return 0;
}
|
1a8d433b57079745f33a98d7b744b2cb189e683f
|
7d81ea9a1f9a519ecdd6913234dff15ad9285a2e
|
/C++/Code/referenceWrapperClass.cpp
|
d53733fe717ca07c189e8b18149bbba43b1e8a36
|
[] |
no_license
|
rajeev921/Algorithms
|
ddbaeaa7fd9809432b348275b1effb72d9d70881
|
7ca5beefda4093bc60a401acaf0afc7babf0129f
|
refs/heads/master
| 2021-07-13T16:40:34.846452
| 2021-02-02T20:25:22
| 2021-02-02T20:25:22
| 229,635,311
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,309
|
cpp
|
referenceWrapperClass.cpp
|
#include <functional>
#include <iostream>
#include <string>
class Bad{
public:
Bad(std::string& s):message(s){}
private:
std::string& message;
};
class Good{
public:
Good(std::string& s):message(s){}
std::string getMessage(){
return message.get();
}
void changeMessage(std::string s){
message.get()= s;
}
private:
std::reference_wrapper<std::string> message;
};
int main(){
std::cout << std::endl;
std::string bad1{"bad1"};
std::string bad2{"bad2"};
Bad b1(bad1);
Bad b2(bad2);
// will not compile, because of reference
//b1 = b2;
std::string good1{"good1"};
std::string good2{"good2"};
Good g1(good1);
Good g2(good2);
std::cout << "g1.getMessage(): " << g1.getMessage() << std::endl;
std::cout << "g2.getMessage(): " << g2.getMessage() << std::endl;
std::cout << std::endl;
std::cout << "g2= g1" << std::endl;
g2= g1;
std::cout << "g1.getMessage(): " << g1.getMessage() << std::endl;
std::cout << "g2.getMessage(): " << g2.getMessage() << std::endl;
std::cout << std::endl;
g1.changeMessage("veryGood");
std::cout << "g1.changeMessage(\"veryGood\")" << std::endl;
std::cout << "g1.getMessage(): " << g1.getMessage() << std::endl;
std::cout << "g2.getMessage(): " << g2.getMessage() << std::endl;
std::cout << std::endl;
}
|
98a4d6bb286b9092924be0eb454374752d8af48d
|
170047df76e147fed86a9eff3bf985e7b1b2a463
|
/include/scene/sky/Clouds.h
|
5864ba60e7cf64573ab89aad19e151253aff7190
|
[
"MIT"
] |
permissive
|
hvidal/GameEngine3D
|
7c68be5ffd362eaea1e818d75ae34d4b1217f628
|
1794ad891d2200260be935283645a03af3ebcfcc
|
refs/heads/master
| 2023-02-12T19:42:25.915763
| 2021-01-14T04:37:42
| 2021-01-14T04:37:42
| 275,481,813
| 6
| 2
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,949
|
h
|
Clouds.h
|
#ifndef GAMEDEV3D_CLOUDS_H
#define GAMEDEV3D_CLOUDS_H
#include "../SceneObject.h"
class Clouds: public SceneObject {
struct Particle {
btVector3 position;
float dimension[3]; // width, height, textureNumber
float cameraDistance;
Particle(const btVector3& v) {
position = v;
}
bool operator<(const Particle& p) const {
// Sort in reverse order : far particles drawn first.
return this->cameraDistance > p.cameraDistance;
}
void write(ISerializer* serializer) const {
serializer->write(position);
serializer->write(dimension[0]);
serializer->write(dimension[1]);
serializer->write(dimension[2]);
}
static Particle read(ISerializer* serializer) {
btVector3 position;
serializer->read(position);
Particle p(std::move(position));
serializer->read(p.dimension[0]);
serializer->read(p.dimension[1]);
serializer->read(p.dimension[2]);
return p;
}
};
std::vector<Particle> mParticles;
std::pair<float,float> mAltitudeRange;
std::unique_ptr<ITexture> mTexture[4];
std::unique_ptr<IShader> mShader;
GLuint mVbo; // vertex buffer object
GLuint mPbo; // position buffer object
void addCloud(float, const btVector3&, int, float, float);
public:
static const std::string& SERIALIZE_ID;
Clouds(const std::pair<float,float>&);
virtual ~Clouds();
void bind();
virtual void createClouds(float, float, float, unsigned int);
virtual void renderOpaque(const ICamera *camera, const ISky *sky, const IShadowMap *shadowMap, const ISurfaceReflection* surfaceReflection, const GameState &gameState) override;
virtual void renderTranslucent(const ICamera* camera, const ISky *sky, const IShadowMap* shadowMap, const ISurfaceReflection* surfaceReflection, const GameState& gameState) override;
virtual void write(ISerializer *serializer) const override;
virtual const std::string& serializeID() const noexcept override;
static std::pair<std::string,Factory> factory();
};
#endif
|
d23614af34c2692b55255ecc9ef4ecdd21ab045d
|
4984f7a38f655fe9aa6231175315651039f57a55
|
/tst/FDMappingTest.cpp
|
23a595f5e652ce5f62db65517f14c53d8aea9fb9
|
[] |
no_license
|
quanshuituantuan/netlib
|
8373d0acf1332a1b60f1446b7777a1da9654a6ef
|
216d19e581b1c17e1a4d7670444bfbf8fe387417
|
refs/heads/master
| 2022-12-04T11:16:52.250550
| 2020-08-15T05:34:44
| 2020-08-15T05:34:44
| 264,667,122
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,274
|
cpp
|
FDMappingTest.cpp
|
#include <gtest/gtest.h>
#include "FDMapping.h"
using namespace EventLoop;
using namespace testing;
class FDMappingTest: public Test
{
};
TEST_F(FDMappingTest, create)
{
FDMapping fdmapping;
}
TEST_F(FDMappingTest, add)
{
FDMapping fdmapping;
int fd(0);
Context *fdlistener(nullptr);
uint32_t event(0);
fdmapping.add(fd, fdlistener, event);
EXPECT_EQ(1, fdmapping.count());
}
TEST_F(FDMappingTest, addAlreadyExist)
{
FDMapping fdmapping;
int fd(0);
Context *fdlistener(nullptr);
uint32_t event(1);
fdmapping.add(fd, fdlistener, event);
event = 2;
fdmapping.add(fd, fdlistener, event);
EXPECT_EQ(1, fdmapping.count());
EXPECT_EQ(1|2, fdmapping.getEvent(fd));
}
TEST_F(FDMappingTest, modify)
{
FDMapping fdmapping;
int fd(0);
Context *fdlistener(nullptr);
uint32_t event(1);
fdmapping.add(fd, fdlistener, event);
event = 2;
fdmapping.modify(fd, event);
EXPECT_EQ(1, fdmapping.count());
EXPECT_EQ(2, fdmapping.getEvent(fd));
}
TEST_F(FDMappingTest, delTest)
{
FDMapping fdmapping;
int fd(0);
Context *fdlistener(nullptr);
uint32_t event(1);
fdmapping.add(fd, fdlistener, event);
fdmapping.del(fd);
EXPECT_EQ(0, fdmapping.count());
}
|
3bec143a9b6a97522df170594d231c7ac6373772
|
837162776da55243444a7dce3e98c69f25071d17
|
/src/runmodule/OutRetrive.cpp
|
aef66d979535aec42a986ad8ace3a09c5ec48a69
|
[] |
no_license
|
vppatil/temVijMods
|
e1b6a10559c2afc29854ae77e107e4c4c747505c
|
5f9abc23d7b626feaa3d1e58a860aa945068cedc
|
refs/heads/master
| 2020-12-24T17:17:19.553771
| 2014-02-20T04:25:17
| 2014-02-20T04:25:17
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 24,902
|
cpp
|
OutRetrive.cpp
|
/*
* This is for
*/
#include "OutRetrive.h"
OutRetrive::OutRetrive(){
};
OutRetrive::~OutRetrive(){
};
void OutRetrive::setDimensionData(CohortData *cdp){
cd = cdp;
};
void OutRetrive::setProcessData(const int & ip, EnvData *edp, BgcData *bdp){
if (ip>=0) {
ed[ip] = edp;
bd[ip] = bdp;
} else {
edall = edp;
bdall = bdp;
}
};
void OutRetrive::setFireData(FirData *fdp){
fd = fdp;
};
void OutRetrive::setRestartOutData(RestartData *resodp){
resod = resodp;
};
void OutRetrive::setRegnOutData(OutDataRegn *regnodp){
regnod = regnodp;
};
// the following is needed, because daily output is done in the last day of the month, and then
// data storing is the best choice
void OutRetrive::assignSiteDlyOutputBuffer_Env(snwstate_dim d_snow, const int &ipft, const int &iday){
if (ipft<0) {
envoddlyall[iday].d_snow = d_snow;
envoddlyall[iday].d_atms = edall->d_atms;
envoddlyall[iday].d_vegs = edall->d_vegs;
envoddlyall[iday].d_snws = edall->d_snws;
envoddlyall[iday].d_sois = edall->d_sois;
envoddlyall[iday].d_atmd = edall->d_atmd;
envoddlyall[iday].d_vegd = edall->d_vegd;
envoddlyall[iday].d_snwd = edall->d_snwd;
envoddlyall[iday].d_soid = edall->d_soid;
envoddlyall[iday].d_l2a = edall->d_l2a;
envoddlyall[iday].d_a2l = edall->d_a2l;
envoddlyall[iday].d_a2v = edall->d_a2v;
envoddlyall[iday].d_v2a = edall->d_v2a;
envoddlyall[iday].d_v2g = edall->d_v2g;
envoddlyall[iday].d_soi2l = edall->d_soi2l;
envoddlyall[iday].d_soi2a = edall->d_soi2a;
envoddlyall[iday].d_snw2a = edall->d_snw2a;
envoddlyall[iday].d_snw2soi = edall->d_snw2soi;
} else {
envoddly[ipft][iday].d_snow = d_snow;
envoddly[ipft][iday].d_atms = ed[ipft]->d_atms;
envoddly[ipft][iday].d_vegs = ed[ipft]->d_vegs;
envoddly[ipft][iday].d_snws = ed[ipft]->d_snws;
envoddly[ipft][iday].d_sois = ed[ipft]->d_sois;
envoddly[ipft][iday].d_atmd = ed[ipft]->d_atmd;
envoddly[ipft][iday].d_vegd = ed[ipft]->d_vegd;
envoddly[ipft][iday].d_snwd = ed[ipft]->d_snwd;
envoddly[ipft][iday].d_soid = ed[ipft]->d_soid;
envoddly[ipft][iday].d_l2a = ed[ipft]->d_l2a;
envoddly[ipft][iday].d_a2l = ed[ipft]->d_a2l;
envoddly[ipft][iday].d_a2v = ed[ipft]->d_a2v;
envoddly[ipft][iday].d_v2a = ed[ipft]->d_v2a;
envoddly[ipft][iday].d_v2g = ed[ipft]->d_v2g;
envoddly[ipft][iday].d_soi2l = ed[ipft]->d_soi2l;
envoddly[ipft][iday].d_soi2a = ed[ipft]->d_soi2a;
envoddly[ipft][iday].d_snw2a = ed[ipft]->d_snw2a;
envoddly[ipft][iday].d_snw2soi = ed[ipft]->d_snw2soi;
}
};
void OutRetrive::updateRegnOutputBuffer(const int & im){
if (im==0) {
regnod->chtid = cd->chtid;
regnod->year = cd->year;
}
regnod->month[im] = im;
if (im==11) {
regnod->yrsdist =cd->yrsdist;
}
//
for (int ip=0; ip<NUM_PFT; ip++) {
if (im==11 && regnod->outvarlist[I_growstart]==1) { // yearly
regnod->growstart[0][ip]=ed[ip]->y_soid.rtdpgrowstart;
} else if (regnod->outvarlist[I_growstart]==2) { // monthly
regnod->growstart[im][ip]=ed[ip]->m_soid.rtdpgrowstart;
}
if (im==11 && regnod->outvarlist[I_growend]==1) {
regnod->growend[0][ip]=ed[ip]->y_soid.rtdpgrowend;
} else if (regnod->outvarlist[I_growend]==2) {
regnod->growend[im][ip]=ed[ip]->m_soid.rtdpgrowend;
}
if (im==11 && regnod->outvarlist[I_vegcov]==1) {
regnod->vegcov[0][ip]=cd->y_veg.vegcov[ip];
} else if (regnod->outvarlist[I_vegcov]==2) {
regnod->vegcov[im][ip]=cd->m_veg.vegcov[ip];
}
if (im==11 && regnod->outvarlist[I_vegage]==1) {
regnod->vegage[0][ip]=cd->y_veg.vegage[ip];
} else if (regnod->outvarlist[I_vegage]==2) {
regnod->vegage[im][ip]=cd->m_veg.vegage[ip];
}
if (im==11 && regnod->outvarlist[I_lai]==1) {
regnod->lai[0][ip] = cd->y_veg.lai[ip];
} else if (regnod->outvarlist[I_lai]==2) {
regnod->lai[im][ip] = cd->m_veg.lai[ip];
}
//
if (im==11 && regnod->outvarlist[I_vegc]==1){
regnod->vegc[0][ip] = bd[ip]->y_vegs.call;
} else if (regnod->outvarlist[I_vegc]==2) {
regnod->vegc[im][ip]= bd[ip]->m_vegs.call;
}
if (im==11 && regnod->outvarlist[I_leafc]==1){
regnod->leafc[0][ip] = bd[ip]->y_vegs.c[I_leaf];
} else if (regnod->outvarlist[I_leafc]==2) {
regnod->leafc[im][ip]= bd[ip]->m_vegs.c[I_leaf];
}
if (im==11 && regnod->outvarlist[I_stemc]==1){
regnod->stemc[0][ip] = bd[ip]->y_vegs.c[I_stem];
} else if (regnod->outvarlist[I_stemc]==2) {
regnod->stemc[im][ip]= bd[ip]->m_vegs.c[I_stem];
}
if (im==11 && regnod->outvarlist[I_rootc]==1){
regnod->rootc[0][ip] = bd[ip]->y_vegs.c[I_root];
} else if (regnod->outvarlist[I_rootc]==2) {
regnod->rootc[im][ip]= bd[ip]->m_vegs.c[I_root];
}
if (im==11 && regnod->outvarlist[I_vegn]==1){
regnod->vegn[0][ip] = bd[ip]->y_vegs.nall;
} else if (regnod->outvarlist[I_vegn]==2) {
regnod->vegn[im][ip] = bd[ip]->m_vegs.nall;
}
if (im==11 && regnod->outvarlist[I_labn]==1){
regnod->labn[0][ip] = bd[ip]->y_vegs.labn;
} else if (regnod->outvarlist[I_labn]==2) {
regnod->labn[im][ip] = bd[ip]->m_vegs.labn;
}
if (im==11 && regnod->outvarlist[I_leafn]==1){
regnod->leafn[0][ip] = bd[ip]->y_vegs.strn[I_leaf];
} else if (regnod->outvarlist[I_leafn]==2) {
regnod->leafn[im][ip] = bd[ip]->m_vegs.strn[I_leaf];
}
if (im==11 && regnod->outvarlist[I_stemn]==1){
regnod->stemn[0][ip] = bd[ip]->y_vegs.strn[I_stem];
} else if (regnod->outvarlist[I_stemn]==2) {
regnod->stemn[im][ip] = bd[ip]->m_vegs.strn[I_stem];
}
if (im==11 && regnod->outvarlist[I_rootn]==1){
regnod->rootn[0][ip] = bd[ip]->y_vegs.strn[I_root];
} else if (regnod->outvarlist[I_rootn]==2) {
regnod->rootn[im][ip] = bd[ip]->m_vegs.strn[I_root];
}
if (im==11 && regnod->outvarlist[I_gpp]==1){
regnod->gpp[0][ip] = bd[ip]->y_a2v.gppall;
} else if (regnod->outvarlist[I_gpp]==2) {
regnod->gpp[im][ip] = bd[ip]->m_a2v.gppall;
}
if (im==11 && regnod->outvarlist[I_npp]==1){
regnod->npp[0][ip] = bd[ip]->y_a2v.nppall;
} else if (regnod->outvarlist[I_npp]==2) {
regnod->npp[im][ip] = bd[ip]->m_a2v.nppall;
}
if (im==11 && regnod->outvarlist[I_ltrfalc]==1){
regnod->ltrfalc[0][ip] = bd[ip]->y_v2soi.ltrfalcall;
} else if (regnod->outvarlist[I_ltrfalc]==2) {
regnod->ltrfalc[im][ip] = bd[ip]->m_v2soi.ltrfalcall;
}
if (im==11 && regnod->outvarlist[I_ltrfaln]==1){
regnod->ltrfaln[0][ip] = bd[ip]->y_v2soi.ltrfalnall;
} else if (regnod->outvarlist[I_ltrfaln]==2) {
regnod->ltrfaln[im][ip] = bd[ip]->m_v2soi.ltrfalnall;
}
if (im==11 && regnod->outvarlist[I_nuptake]==1){
regnod->nuptake[0][ip] = bd[ip]->y_soi2v.lnuptake+bd[ip]->y_soi2v.snuptakeall;
} else if (regnod->outvarlist[I_nuptake]==2) {
regnod->nuptake[im][ip] = bd[ip]->m_soi2v.lnuptake+bd[ip]->m_soi2v.snuptakeall;
}
}
// ground-soil portion
if (im==11 && regnod->outvarlist[I_rh]==1){
regnod->rh[0] = bdall->y_soi2a.rhrawcsum //note: 'bd' soil portion MUST BE exactly SAME for all PFTs
+bdall->y_soi2a.rhsomasum
+bdall->y_soi2a.rhsomprsum
+bdall->y_soi2a.rhsomcrsum;
} else if (regnod->outvarlist[I_rh]==2) {
regnod->rh[im] = bdall->m_soi2a.rhrawcsum
+bdall->m_soi2a.rhsomasum
+bdall->m_soi2a.rhsomprsum
+bdall->m_soi2a.rhsomcrsum;
}
if (im==11 && regnod->outvarlist[I_permafrost]==1) {
regnod->permafrost[0] = edall->y_soid.permafrost;
} else if (regnod->outvarlist[I_permafrost]==2) {
regnod->permafrost[im]= edall->m_soid.permafrost;
}
if (im==11 && regnod->outvarlist[I_mossdz]==1){
regnod->mossdz[0] = cd->y_soil.mossthick;
} else if (regnod->outvarlist[I_mossdz]==2) {
regnod->mossdz[im] = cd->m_soil.mossthick;
}
if (im==11 && regnod->outvarlist[I_oshlwdz]==1){
regnod->oshlwdz[0] = cd->y_soil.shlwthick;
} else if (regnod->outvarlist[I_oshlwdz]==2) {
regnod->oshlwdz[im]= cd->m_soil.shlwthick;
}
if (im==11 && regnod->outvarlist[I_odeepdz]==1){
regnod->odeepdz[0] = cd->y_soil.deepthick;
} else if (regnod->outvarlist[I_odeepdz]==2) {
regnod->odeepdz[im] = cd->m_soil.deepthick;
}
///////////////////
if (im==11 && regnod->outvarlist[I_mineadz]==1){
regnod->mineadz[0] = cd->y_soil.mineathick;
} else if (regnod->outvarlist[I_mineadz]==2) {
regnod->mineadz[im]= cd->m_soil.mineathick;
}
if (im==11 && regnod->outvarlist[I_minebdz]==1){
regnod->minebdz[0] = cd->y_soil.minebthick;
} else if (regnod->outvarlist[I_minebdz]==2) {
regnod->minebdz[im]= cd->m_soil.minebthick;
}
if (im==11 && regnod->outvarlist[I_minecdz]==1){
regnod->minecdz[0] = cd->y_soil.minecthick;
} else if (regnod->outvarlist[I_minecdz]==2) {
regnod->minecdz[im]= cd->m_soil.minecthick;
}
if (im==11 && regnod->outvarlist[I_oshlwc]==1){
regnod->oshlwc[0] = bdall->y_soid.shlwc;
} else if (regnod->outvarlist[I_oshlwc]==2) {
regnod->oshlwc[im]= bdall->m_soid.shlwc;
}
if (im==11 && regnod->outvarlist[I_odeepc]==1){
regnod->odeepc[0] = bdall->y_soid.deepc;
} else if (regnod->outvarlist[I_odeepc]==2) {
regnod->odeepc[im]= bdall->m_soid.deepc;
}
if (im==11 && regnod->outvarlist[I_mineac]==1){
regnod->mineac[0] = cd->y_soil.shlwthick;
} else if (regnod->outvarlist[I_mineac]==2) {
regnod->mineac[im] = edall->m_soid.permafrost;
}
if (im==11 && regnod->outvarlist[I_minebc]==1){
regnod->minebc[0] = cd->y_soil.shlwthick;
} else if (regnod->outvarlist[I_minebc]==2) {
regnod->minebc[im] = edall->m_soid.permafrost;
}
if (im==11 && regnod->outvarlist[I_minecc]==1){
regnod->minecc[0] = cd->y_soil.shlwthick;
} else if (regnod->outvarlist[I_minecc]==2) {
regnod->minecc[im] = edall->m_soid.permafrost;
}
if (im==11 && regnod->outvarlist[I_orgn]==1){
regnod->orgn[0] = bdall->y_soid.orgnsum;
} else if (regnod->outvarlist[I_orgn]==2) {
regnod->orgn[im]= bdall->m_soid.orgnsum;
}
if (im==11 && regnod->outvarlist[I_avln]==1){
regnod->avln[0] = bdall->y_soid.avlnsum;
} else if (regnod->outvarlist[I_avln]==2) {
regnod->avln[im]= bdall->m_soid.avlnsum;
}
if (im==11 && regnod->outvarlist[I_netnmin]==1){
regnod->netnmin[0] = bdall->y_soi2soi.netnminsum;
} else if (regnod->outvarlist[I_netnmin]==2) {
regnod->netnmin[im]= bdall->m_soi2soi.netnminsum;
}
if (im==11 && regnod->outvarlist[I_orgninput]==1){
regnod->orgninput[0] = bdall->y_a2soi.orgninput;
} else if (regnod->outvarlist[I_orgninput]==2) {
regnod->orgninput[im]= bdall->m_a2soi.orgninput;
}
if (im==11 && regnod->outvarlist[I_avlninput]==1){
regnod->avlninput[0] = bdall->y_a2soi.avlninput;
} else if (regnod->outvarlist[I_avlninput]==2) {
regnod->avlninput[im]= bdall->m_a2soi.avlninput;
}
if (im==11 && regnod->outvarlist[I_doclost]==1){
regnod->doclost[0] = bdall->y_soi2l.doclost;
} else if (regnod->outvarlist[I_doclost]==2) {
regnod->doclost[im]= bdall->m_soi2l.doclost;
}
if (im==11 && regnod->outvarlist[I_orgnlost]==1){
regnod->orgnlost[0] = bdall->y_soi2l.orgnlost;
} else if (regnod->outvarlist[I_orgnlost]==2) {
regnod->orgnlost[im]= bdall->m_soi2l.orgnlost;
}
if (im==11 && regnod->outvarlist[I_avlnlost]==1){
regnod->avlnlost[0] = bdall->y_soi2l.avlnlost;
} else if (regnod->outvarlist[I_avlnlost]==2) {
regnod->avlnlost[im]= bdall->m_soi2l.avlnlost;
}
//
if (im==11 && regnod->outvarlist[I_eet]==1){
regnod->eet[0] = edall->y_l2a.eet;
} else if (regnod->outvarlist[I_eet]==2) {
regnod->eet[im]= edall->m_l2a.eet;
}
if (im==11 && regnod->outvarlist[I_pet]==1){
regnod->pet[0] = edall->y_l2a.pet;
} else if (regnod->outvarlist[I_pet]==2) {
regnod->pet[im]= edall->m_l2a.pet;
}
if (im==11 && regnod->outvarlist[I_qinfl]==1){
regnod->qinfl[0] = edall->y_soi2l.qinfl;
} else if (regnod->outvarlist[I_qinfl]==2) {
regnod->qinfl[im]= edall->m_soi2l.qinfl;
}
if (im==11 && regnod->outvarlist[I_qdrain]==1){
regnod->qdrain[0] = edall->y_soi2l.qdrain;
} else if (regnod->outvarlist[I_qdrain]==2) {
regnod->qdrain[im]= edall->m_soi2l.qdrain;
}
if (im==11 && regnod->outvarlist[I_qrunoff]==1){
regnod->qrunoff[0] = edall->y_soi2l.qover;
} else if (regnod->outvarlist[I_qrunoff]==2) {
regnod->qrunoff[im]= edall->m_soi2l.qover;
}
if (im==11 && regnod->outvarlist[I_snwthick]==1){
regnod->snwthick[0] = cd->y_snow.thick;
} else if (regnod->outvarlist[I_snwthick]==2) {
regnod->snwthick[im]= cd->m_snow.thick;
}
if (im==11 && regnod->outvarlist[I_swe]==1){
regnod->swe[0] = edall->y_snws.swesum;
} else if (regnod->outvarlist[I_swe]==2) {
regnod->swe[im] = edall->m_snws.swesum;
}
if (im==11 && regnod->outvarlist[I_wtd]==1){
regnod->wtd[0] = edall->y_sois.watertab;
} else if (regnod->outvarlist[I_wtd]==2) {
regnod->wtd[im]= edall->m_sois.watertab;
}
if (im==11 && regnod->outvarlist[I_alc]==1){
regnod->alc[0] = edall->y_soid.alc;
} else if (regnod->outvarlist[I_alc]==2) {
regnod->alc[im]= edall->m_soid.alc;
}
if (im==11 && regnod->outvarlist[I_ald]==1){
regnod->ald[0] = edall->y_soid.ald;
} else if (regnod->outvarlist[I_ald]==2) {
regnod->ald[im]= edall->m_soid.ald;
}
///
if (im==11 && regnod->outvarlist[I_vwcshlw]==1){
regnod->vwcshlw[0] = edall->y_soid.vwcshlw;
} else if (regnod->outvarlist[I_vwcshlw]==2) {
regnod->vwcshlw[im]= edall->m_soid.vwcshlw;
}
if (im==11 && regnod->outvarlist[I_vwcdeep]==1){
regnod->vwcdeep[0] = edall->y_soid.vwcdeep;
} else if (regnod->outvarlist[I_vwcdeep]==2) {
regnod->vwcdeep[im] = edall->m_soid.vwcdeep;
}
if (im==11 && regnod->outvarlist[I_vwcminea]==1){
regnod->vwcminea[0] = edall->y_soid.vwcminea;
} else if (regnod->outvarlist[I_vwcminea]==2) {
regnod->vwcminea[im]= edall->m_soid.vwcminea;
}
if (im==11 && regnod->outvarlist[I_vwcmineb]==1){
regnod->vwcmineb[0] = edall->y_soid.vwcmineb;
} else if (regnod->outvarlist[I_vwcmineb]==2) {
regnod->vwcmineb[im]= edall->m_soid.vwcmineb;
}
if (im==11 && regnod->outvarlist[I_vwcminec]==1){
regnod->vwcminec[0] = edall->y_soid.vwcminec;
} else if (regnod->outvarlist[I_vwcminec]==2) {
regnod->vwcminec[im]= edall->m_soid.vwcminec;
}
if (im==11 && regnod->outvarlist[I_tshlw]==1){
regnod->tshlw[0] = edall->y_soid.tshlw;
} else if (regnod->outvarlist[I_tshlw]==2) {
regnod->tshlw[im] = edall->y_soid.tshlw;
}
if (im==11 && regnod->outvarlist[I_tdeep]==1){
regnod->tdeep[0] = edall->y_soid.tdeep;
} else if (regnod->outvarlist[I_tdeep]==2) {
regnod->tdeep[im] = edall->m_soid.tdeep;
}
if (im==11 && regnod->outvarlist[I_tminea]==1){
regnod->tminea[0] = edall->y_soid.tminea;
} else if (regnod->outvarlist[I_tminea]==2) {
regnod->tminea[im] = edall->m_soid.tminea;
}
if (im==11 && regnod->outvarlist[I_tmineb]==1){
regnod->tmineb[0] = edall->y_soid.tmineb;
} else if (regnod->outvarlist[I_tmineb]==2) {
regnod->tmineb[im] = edall->m_soid.tmineb;
}
if (im==11 && regnod->outvarlist[I_tminec]==1){
regnod->tminec[0] = edall->y_soid.tminec;
} else if (regnod->outvarlist[I_tminec]==2) {
regnod->tminec[im] = edall->m_soid.tminec;
}
if (im==11 && regnod->outvarlist[I_hkshlw]==1){
regnod->hkshlw[0] = edall->y_soid.hkshlw;
} else if (regnod->outvarlist[I_hkshlw]==2) {
regnod->hkshlw[im] = edall->m_soid.hkshlw;
}
if (im==11 && regnod->outvarlist[I_hkdeep]==1){
regnod->hkdeep[0] = edall->y_soid.hkdeep;
} else if (regnod->outvarlist[I_hkdeep]==2) {
regnod->hkdeep[im] = edall->m_soid.hkdeep;
}
if (im==11 && regnod->outvarlist[I_hkminea]==1){
regnod->hkminea[0] = edall->y_soid.hkminea;
} else if (regnod->outvarlist[I_hkminea]==2) {
regnod->hkminea[im] = edall->m_soid.hkminea;
}
if (im==11 && regnod->outvarlist[I_hkmineb]==1){
regnod->hkmineb[0] = edall->y_soid.hkmineb;
} else if (regnod->outvarlist[I_hkmineb]==2) {
regnod->hkmineb[im] = edall->m_soid.hkmineb;
}
if (im==11 && regnod->outvarlist[I_hkminec]==1){
regnod->hkminec[0] = edall->y_soid.hkminec;
} else if (regnod->outvarlist[I_hkminec]==2) {
regnod->hkminec[im] = edall->m_soid.hkminec;
}
if (im==11 && regnod->outvarlist[I_tcshlw]==1){
regnod->tcshlw[0] = edall->y_soid.tcshlw;
} else if (regnod->outvarlist[I_tcshlw]==2) {
regnod->tcshlw[im] = edall->m_soid.tcshlw;
}
if (im==11 && regnod->outvarlist[I_tcdeep]==1){
regnod->tcdeep[0] = edall->y_soid.tcdeep;
} else if (regnod->outvarlist[I_tcdeep]==2) {
regnod->tcdeep[im] = edall->m_soid.tcdeep;
}
if (im==11 && regnod->outvarlist[I_tcminea]==1){
regnod->tcminea[0] = edall->y_soid.tcminea;
} else if (regnod->outvarlist[I_tcminea]==2) {
regnod->tcminea[im] = edall->m_soid.tcminea;
}
if (im==11 && regnod->outvarlist[I_tcmineb]==1){
regnod->tcmineb[0] = edall->y_soid.tcmineb;
} else if (regnod->outvarlist[I_tcmineb]==2) {
regnod->tcmineb[im] = edall->m_soid.tcmineb;
}
if (im==11 && regnod->outvarlist[I_tcminec]==1){
regnod->tcminec[0] = edall->y_soid.tcminec;
} else if (regnod->outvarlist[I_tcminec]==2) {
regnod->tcminec[im] = edall->m_soid.tcminec;
}
if (im==11 && regnod->outvarlist[I_tbotrock]==1){
regnod->tbotrock[0] = edall->y_soid.tbotrock;
} else if (regnod->outvarlist[I_tbotrock]==2) {
regnod->tbotrock[im] = edall->m_soid.tbotrock;
}
///////////////////////
if (im==11 && regnod->outvarlist[I_burnthick]==1){
regnod->burnthick[0] = fd->fire_soid.burnthick;
} else if (regnod->outvarlist[I_burnthick]==2) {
regnod->burnthick[im]= fd->fire_soid.burnthick;
}
if (im==11 && regnod->outvarlist[I_burnsoic]==1){
regnod->burnsoic[0] = fd->fire_soi2a.orgc;
} else if (regnod->outvarlist[I_burnsoic]==2) {
regnod->burnsoic[im] = fd->fire_soi2a.orgc;
}
if (im==11 && regnod->outvarlist[I_burnvegc]==1){
regnod->burnvegc[0] = fd->fire_v2a.orgc;
} else if (regnod->outvarlist[I_burnvegc]==2) {
regnod->burnvegc[im]= fd->fire_v2a.orgc;
}
if (im==11 && regnod->outvarlist[I_burnsoin]==1){
regnod->burnsoin[0] = fd->fire_soi2a.orgn;
} else if (regnod->outvarlist[I_burnsoin]==2) {
regnod->burnsoin[im]= fd->fire_soi2a.orgn;
}
if (im==11 && regnod->outvarlist[I_burnvegn]==1){
regnod->burnvegn[0] = fd->fire_v2a.orgn;
} else if (regnod->outvarlist[I_burnvegn]==2) {
regnod->burnvegn[im]= fd->fire_v2a.orgn;
}
if (im==11 && regnod->outvarlist[I_burnretainc]==1){
regnod->burnretainc[0] = fd->fire_v2soi.abvc+fd->fire_v2soi.blwc; //retained abvc is burned residue, retained blwc is burn-caused root death
} else if (regnod->outvarlist[I_burnretainc]==2) {
regnod->burnretainc[im]= fd->fire_v2soi.abvc+fd->fire_v2soi.blwc;
}
if (im==11 && regnod->outvarlist[I_burnretainn]==1){
regnod->burnretainn[0] = fd->fire_v2soi.abvn+fd->fire_v2soi.blwn;
} else if (regnod->outvarlist[I_burnretainn]==2) {
regnod->burnretainn[im]= fd->fire_v2soi.abvn+fd->fire_v2soi.blwn;
}
};
// NOTE: 'resod', restartoutput data, a dataset to resume a complete model run if model is paused
// This is useful and very needed for carrying out a series of model implementation, i.e., from eq->spinup->transient->scenario runs
// OR, potentially the model can run spatially for one time-step (rather than in time series for ONE cohort)
void OutRetrive::updateRestartOutputBuffer(){
resod->reinitValue();
//
resod->chtid = cd->chtid;
// atm
resod->dsr = edall->d_atms.dsr;
resod->firea2sorgn = fd->fire_a2soi.orgn; //this is 'fire_a2soi.orgn' to re-deposit fire-emitted N in one FRI
//vegegetation
resod->yrsdist = cd->yrsdist;
for (int ip=0; ip<NUM_PFT; ip++) {
resod->ifwoody[ip] = cd->m_veg.ifwoody[ip];
resod->ifdeciwoody[ip]= cd->m_veg.ifdeciwoody[ip];
resod->ifperenial[ip] = cd->m_veg.ifperenial[ip];
resod->nonvascular[ip]= cd->m_veg.nonvascular[ip];
resod->vegage[ip] = cd->m_veg.vegage[ip];
resod->vegcov[ip] = cd->m_veg.vegcov[ip];
resod->lai[ip] = cd->m_veg.lai[ip];
for (int i=0; i<MAX_ROT_LAY; i++) {
resod->rootfrac[i][ip] = cd->m_veg.frootfrac[i][ip];
}
resod->vegwater[ip] = ed[ip]->m_vegs.rwater; //canopy water - 'vegs_env'
resod->vegsnow[ip] = ed[ip]->m_vegs.snow; //canopy snow - 'vegs_env'
for (int i=0; i<NUM_PFT_PART; i++) {
resod->vegc[i][ip] = bd[ip]->m_vegs.c[i]; // - 'vegs_bgc'
resod->strn[i][ip] = bd[ip]->m_vegs.strn[i];
}
resod->labn[ip] = bd[ip]->m_vegs.labn;
resod->deadc[ip] = bd[ip]->m_vegs.deadc;
resod->deadn[ip] = bd[ip]->m_vegs.deadn;
resod->eetmx[ip] = cd->m_vegd.eetmx[ip];
resod->topt[ip] = cd->m_vegd.topt[ip];
resod->unnormleafmx[ip] = cd->m_vegd.unnormleafmx[ip];
resod->growingttime[ip] = cd->m_vegd.growingttime[ip];
resod->foliagemx[ip] = cd->m_vegd.foliagemx[ip]; // this is for f(foliage) in GPP to be sure f(foliage) not going down
deque<double> tmpdeque1 = cd->toptque[ip];
int recnum = tmpdeque1.size();
for (int i=0; i<recnum; i++) {
resod->toptA[i][ip] = tmpdeque1[i];
}
deque<double> tmpdeque2 = cd->prvunnormleafmxque[ip];
recnum = tmpdeque2.size();
for (int i=0; i<recnum; i++) {
resod->unnormleafmxA[i][ip] = tmpdeque2[i];
}
deque<double> tmpdeque3 = cd->prvgrowingttimeque[ip];
recnum = tmpdeque3.size();
for (int i=0; i<recnum; i++) {
resod->growingttimeA[i][ip]= tmpdeque3[i];
}
deque<double> tmpdeque4 = cd->prveetmxque[ip];
recnum = tmpdeque4.size();
for (int i=0; i<recnum; i++) {
resod->eetmxA[i][ip]= tmpdeque4[i];
}
}
// snow - 'restart' from the last point, so be the daily for 'cd' and 'ed', but monthly for 'bd'
resod->numsnwl = cd->d_snow.numsnwl;
resod->snwextramass = cd->d_snow.extramass;
for(int il =0;il<cd->d_snow.numsnwl; il++){
resod->DZsnow[il] = cd->d_snow.dz[il];
resod->AGEsnow[il] = cd->d_snow.age[il];
resod->RHOsnow[il] = cd->d_snow.rho[il];
resod->TSsnow[il] = edall->d_snws.tsnw[il]; // NOTE: for all PFT, ground 'ed' is same, BE sure that is done
resod->LIQsnow[il] = edall->d_snws.snwliq[il];
resod->ICEsnow[il] = edall->d_snws.snwice[il];
}
//ground-soil
resod->numsl = cd->d_soil.numsl; //actual number of soil layers
resod->monthsfrozen = edall->monthsfrozen;
resod->rtfrozendays = edall->rtfrozendays;
resod->rtunfrozendays = edall->rtunfrozendays;
resod->watertab = edall->d_sois.watertab;
for(int il =0;il<cd->d_soil.numsl; il++){
resod->DZsoil[il] = cd->d_soil.dz[il];
resod->AGEsoil[il] = cd->d_soil.age[il];
resod->TYPEsoil[il] = cd->d_soil.type[il];
resod->TEXTUREsoil[il]= cd->d_soil.texture[il];
resod->TSsoil[il] = edall->d_sois.ts[il];
resod->LIQsoil[il] = edall->d_sois.liq[il];
resod->ICEsoil[il] = edall->d_sois.ice[il];
resod->FROZENFRACsoil[il]= edall->d_sois.frozenfrac[il];
}
for(int il =0;il<MAX_ROC_LAY; il++){
resod->TSrock[il] = edall->d_sois.trock[il];
resod->DZrock[il] = ROCKTHICK[il];
}
for(int il =0;il<MAX_NUM_FNT; il++){
resod->frontZ[il] = edall->d_sois.frontsz[il];
resod->frontFT[il] = edall->d_sois.frontstype[il];
}
//
resod->wdebrisc = bdall->m_sois.wdebrisc;
resod->wdebrisn = bdall->m_sois.wdebrisn;
resod->dmossc = bdall->m_sois.dmossc;
resod->dmossn = bdall->m_sois.dmossn;
for(int il =0;il<cd->m_soil.numsl; il++){
resod->rawc[il] = bdall->m_sois.rawc[il];
resod->soma[il] = bdall->m_sois.soma[il];
resod->sompr[il] = bdall->m_sois.sompr[il];
resod->somcr[il] = bdall->m_sois.somcr[il];
resod->orgn[il] = bdall->m_sois.orgn[il];
resod->avln[il] = bdall->m_sois.avln[il];
deque<double> tmpdeque = bdall->prvltrfcnque[il];
int recnum = tmpdeque.size();
for (int i=0; i<recnum; i++) {
resod->prvltrfcnA[i][il]= tmpdeque[i];
}
}
};
|
b3d1c8de3a498412de42f0165b58bcb96989ec50
|
be6af81081c631368616cee582a8e1bcf728fc78
|
/mainform.cpp
|
6685073127e6d95c32798a9410de0ccfda1500f6
|
[] |
no_license
|
Flamio/RepairCards
|
987e7ded1aebe03e330be285fa7e1d90cf81ab35
|
5d060e984043c09c7bf97a292a8921058dec84e3
|
refs/heads/master
| 2020-04-26T14:28:34.282118
| 2020-03-27T19:38:40
| 2020-03-27T19:38:40
| 173,615,500
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 4,791
|
cpp
|
mainform.cpp
|
#include "mainform.h"
#include "ui_mainform.h"
#include "helper.h"
#include <QMessageBox>
MainForm::MainForm(QWidget *parent) :
QDialog(parent),
ui(new Ui::MainForm)
{
ui->setupUi(this);
ui->current_card_index->setValidator(new QIntValidator());
}
MainForm::~MainForm()
{
delete ui;
}
void MainForm::setCard(const RepairCard &card, const QVector<CardMethod> &methods)
{
if (card.returnDate.toString("dd.MM.yyyy") != "")
this->setStyleSheet("QLabel, QLineEdit, QTableWidget, QPlainTextEdit {color:gray} "
" QLineEdit#current_card_index {color:black} QLineEdit#cards_count {color:black}");
else
this->setStyleSheet("QLabel, QLineEdit, QTableWidget, QPlainTextEdit {color:black}");
ui->barcode->setText(card.barCode);
if (card.product.isOwen)
{
auto data = Helper::ParseBarcode(card.barCode);
ui->createMonth->setText(data.month);
ui->createYear->setText("20"+data.year);
}
else
{
ui->createMonth->setText(card.month);
ui->createYear->setText(card.year);
}
ui->client->setText(QString("%1; %2; %3").arg(card.client.name).arg(card.client.phone).arg(card.client.person));
ui->clientCost->setText(QString::number(card.costForClient));
ui->complains->setPlainText(card.complaints);
ui->id->setText(QString::number(card.id));
ui->cards_count->setText(QString("%1").arg(card.allIndexes));
ui->current_card_index->setText(QString("%1").arg(card.currentIndex));
ui->note->setPlainText(card.note);
ui->product->setText(card.product.name);
ui->ready->setText(card.readyDate.toString("dd.MM.yyyy"));
ui->returnDate->setText(card.returnDate.toString("dd.MM.yyyy"));
ui->receive->setText(card.receiveFromClientDate.toString("dd.MM.yyyy"));
ui->state->setText(card.state);
ui->reason->setPlainText(card.reason);
ui->repairCost->setText(QString::number(card.costRepair));
ui->repairer->setText(card.repairer);
ui->receive2->setText(card.receiveFromFactoryDate.toString("dd.MM.yyyy"));
ui->send->setText(card.sendDate.toString("dd.MM.yyyy"));
ui->tableWidget->setRowCount(0);
int i = 0;
for (auto method : methods)
{
auto item = new QTableWidgetItem(method.methodName);
item->setFlags(Qt::ItemIsEnabled);
auto item2 = new QTableWidgetItem(method.description);
item2->setFlags(Qt::ItemIsEnabled);
ui->tableWidget->insertRow(i);
ui->tableWidget->setItem(i,0, item);
ui->tableWidget->setItem(i,1, item2);
ui->tableWidget->setRowHeight(i,20);
i++;
}
}
IMainView *MainForm::newDialog()
{
if (dialog != nullptr)
delete dialog;
dialog = new MainForm(this);
dialog->setIsDialog(true);
dialog->hideNavigationPanel();
return dialog;
}
void MainForm::closeEvent(QCloseEvent *event)
{
if (isDialog)
{
event->accept();
return;
}
QMessageBox::StandardButton reply;
reply = QMessageBox::question(this, "Выход", "Вы действительно хотите закрыть программу?",
QMessageBox::Yes|QMessageBox::No);
if (reply == QMessageBox::Yes)
event->accept();
else
event->ignore();
}
void MainForm::on_pushButton_7_clicked()
{
emit navigation(false);
}
void MainForm::on_pushButton_8_clicked()
{
emit navigation(true);
}
void MainForm::on_pushButton_10_clicked()
{
emit add();
}
void MainForm::on_pushButton_9_clicked()
{
QMessageBox::StandardButton reply;
reply = QMessageBox::question(this, "Удаление", "Вы действительно хотите удалить ремонтную карту?",
QMessageBox::Yes|QMessageBox::No);
if (reply == QMessageBox::Yes)
deleteSignal(ui->id->text().toInt());
}
void MainForm::on_pushButton_clicked()
{
emit edit(ui->id->text().toInt());
}
void MainForm::setIsDialog(bool value)
{
isDialog = value;
}
void MainForm::hideNavigationPanel()
{
ui->frame_2->setVisible(false);
}
void MainForm::on_pushButton_6_clicked()
{
auto type = (PrintType::PrintType)ui->print->currentIndex();
auto cardId = ui->id->text().toInt();
emit print(cardId,type);
}
void MainForm::on_showSendedProducts_clicked()
{
emit showSendedProducts();
}
void MainForm::on_pushButton_2_clicked()
{
emit showExtremeCard(ExtremeCardType::Last);
}
void MainForm::on_pushButton_3_clicked()
{
emit showExtremeCard(ExtremeCardType::First);
}
void MainForm::on_current_card_index_editingFinished()
{
emit showCardByIndex(ui->current_card_index->text().toInt());
}
void MainForm::on_pushButton_4_clicked()
{
callbacks.searchCards();
}
|
b93e54e141864050db28ce7341dfb5f60a801550
|
a802488c68d5c8607e8d4696b8244eaacc9c3ac2
|
/DK/DKFramework/DKTransform.cpp
|
02ae6b4df90845ebfee3c1be9e482819cb3b164a
|
[
"LGPL-2.0-or-later",
"BSD-3-Clause"
] |
permissive
|
Hongtae/DKGL
|
e311c6e528349c8b9e7e8392f1d01ac976e76be1
|
eb33d843622504cd6134accf08c8ec2c98794b55
|
refs/heads/develop
| 2023-04-28T22:02:44.866063
| 2023-01-14T02:11:30
| 2023-01-14T02:11:30
| 30,572,734
| 11
| 3
|
BSD-3-Clause
| 2023-01-18T03:02:10
| 2015-02-10T03:23:18
|
C
|
UTF-8
|
C++
| false
| false
| 6,734
|
cpp
|
DKTransform.cpp
|
//
// File: DKTransform.cpp
// Author: Hongtae Kim (tiff2766@gmail.com)
//
// Copyright (c) 2004-2016 Hongtae Kim. All rights reserved.
//
#include "DKTransform.h"
#include "DKAffineTransform3.h"
#include "DKLinearTransform3.h"
using namespace DKFramework;
const DKTransformUnit DKTransformUnit::identity = DKTransformUnit().Identity();
const DKUSTransform DKUSTransform::identity = DKUSTransform().Identity();
const DKNSTransform DKNSTransform::identity = DKNSTransform().Identity();
////////////////////////////////////////////////////////////////////////////////
// class DKTransformUnit
////////////////////////////////////////////////////////////////////////////////
DKTransformUnit::DKTransformUnit()
: scale(1.0f, 1.0f, 1.0f)
, rotation(0.0f, 0.0f, 0.0f, 1.0f)
, translation(0.0f, 0.0f, 0.0f)
{
}
DKTransformUnit::DKTransformUnit(const DKVector3& s, const DKQuaternion& r, const DKVector3& t)
: scale(s)
, rotation(r)
, translation(t)
{
}
DKMatrix3 DKTransformUnit::Matrix3() const
{
DKMatrix3 mat3 = rotation.Matrix3();
// mat3 = scale * rotation
mat3.m[0][0] *= scale.x;
mat3.m[0][1] *= scale.x;
mat3.m[0][2] *= scale.x;
mat3.m[1][0] *= scale.y;
mat3.m[1][1] *= scale.y;
mat3.m[1][2] *= scale.y;
mat3.m[2][0] *= scale.z;
mat3.m[2][1] *= scale.z;
mat3.m[2][2] *= scale.z;
return mat3;
}
DKMatrix4 DKTransformUnit::Matrix4() const
{
DKMatrix3 mat3 = Matrix3();
return DKMatrix4(
mat3.m[0][0], mat3.m[0][1], mat3.m[0][2], 0.0f,
mat3.m[1][0], mat3.m[1][1], mat3.m[1][2], 0.0f,
mat3.m[2][0], mat3.m[2][1], mat3.m[2][2], 0.0f,
translation.x, translation.y, translation.z, 1.0f);
}
DKTransformUnit DKTransformUnit::Interpolate(const DKTransformUnit& target, float t) const
{
return DKTransformUnit(
scale + ((target.scale - scale) * t),
DKQuaternion::Slerp(rotation, target.rotation, t),
translation + ((target.translation - translation) * t));
}
DKTransformUnit& DKTransformUnit::Identity()
{
scale = DKVector3(1.0f, 1.0f, 1.0f);
rotation = DKQuaternion(0.0f, 0.0f, 0.0f, 1.0f);
translation = DKVector3(0.0f, 0.0f, 0.0f);
return *this;
}
bool DKTransformUnit::operator == (const DKTransformUnit& t) const
{
return t.scale == this->scale && t.rotation == this->rotation && t.translation == this->translation;
}
bool DKTransformUnit::operator != (const DKTransformUnit& t) const
{
return t.scale != this->scale || t.rotation != this->rotation || t.translation != this->translation;
}
////////////////////////////////////////////////////////////////////////////////
// class DKUSTransform
////////////////////////////////////////////////////////////////////////////////
DKUSTransform::DKUSTransform()
: scale(1.0f)
, orientation(0.0f, 0.0f, 0.0f, 1.0f)
, position(0.0f, 0.0f, 0.0f)
{
}
DKUSTransform::DKUSTransform(float s, const DKQuaternion& r, const DKVector3& t)
: scale(s)
, orientation(r)
, position(t)
{
}
DKMatrix3 DKUSTransform::Matrix3() const
{
return orientation.Matrix3() * scale;
}
DKMatrix4 DKUSTransform::Matrix4() const
{
DKMatrix3 mat3 = orientation.Matrix3() * scale;
return DKMatrix4(
mat3.m[0][0], mat3.m[0][1], mat3.m[0][2], 0.0f,
mat3.m[1][0], mat3.m[1][1], mat3.m[1][2], 0.0f,
mat3.m[2][0], mat3.m[2][1], mat3.m[2][2], 0.0f,
position.x, position.y, position.z, 1.0f);
}
DKUSTransform DKUSTransform::Interpolate(const DKUSTransform& target, float t) const
{
return DKUSTransform(
scale + ((target.scale - scale) * t),
DKQuaternion::Slerp(orientation, target.orientation, t),
position + ((target.position - position) * t));
}
DKUSTransform& DKUSTransform::Identity()
{
scale = 1.0f;
orientation = DKQuaternion(0.0f, 0.0f, 0.0f, 1.0f);
position = DKVector3(0.0f, 0.0f, 0.0f);
return *this;
}
DKUSTransform& DKUSTransform::Inverse()
{
scale = 1.0 / scale;
orientation.Conjugate();
position = (-position * scale) * orientation;
return *this;
}
DKUSTransform DKUSTransform::operator * (const DKUSTransform& t) const
{
DKMatrix3 mat3 = t.Matrix3();
return DKUSTransform( scale * t.scale, orientation * t.orientation, position * mat3 + t.position );
}
DKUSTransform& DKUSTransform::operator *= (const DKUSTransform& t)
{
DKMatrix3 mat3 = t.Matrix3();
this->position = this->position * mat3 + t.position;
this->orientation = this->orientation * t.orientation;
this->scale *= t.scale;
return *this;
}
bool DKUSTransform::operator == (const DKUSTransform& t) const
{
return t.scale == this->scale && t.orientation == this->orientation && t.position == this->position;
}
bool DKUSTransform::operator != (const DKUSTransform& t) const
{
return t.scale != this->scale || t.orientation != this->orientation || t.position != this->position;
}
////////////////////////////////////////////////////////////////////////////////
// class DKNSTransform
////////////////////////////////////////////////////////////////////////////////
DKNSTransform::DKNSTransform(const DKQuaternion& r, const DKVector3& t)
: orientation(r), position(t)
{
}
DKNSTransform::DKNSTransform(const DKMatrix3& r, const DKVector3& t)
: orientation(DKLinearTransform3(r).Rotation()), position(t)
{
}
DKNSTransform::DKNSTransform(const DKVector3& t)
: orientation(DKQuaternion::identity), position(t)
{
}
DKNSTransform& DKNSTransform::Identity()
{
orientation.Identity();
position.x = 0;
position.y = 0;
position.z = 0;
return *this;
}
DKNSTransform& DKNSTransform::Inverse()
{
orientation.Conjugate();
position = -position * orientation;
return *this;
}
DKNSTransform DKNSTransform::Interpolate(const DKNSTransform& target, float t) const
{
return DKNSTransform(
DKQuaternion::Slerp(this->orientation, target.orientation, t),
this->position + ((target.position - this->position) * t));
}
DKMatrix3 DKNSTransform::Matrix3() const
{
return orientation.Matrix3();
}
DKMatrix4 DKNSTransform::Matrix4() const
{
DKMatrix3 mat3 = orientation.Matrix3();
return DKMatrix4(
mat3.m[0][0], mat3.m[0][1], mat3.m[0][2], 0.0f,
mat3.m[1][0], mat3.m[1][1], mat3.m[1][2], 0.0f,
mat3.m[2][0], mat3.m[2][1], mat3.m[2][2], 0.0f,
position.x, position.y, position.z, 1.0f);
}
DKNSTransform DKNSTransform::operator * (const DKNSTransform& t) const
{
return DKNSTransform( this->orientation * t.orientation, this->position * t.orientation + t.position);
}
DKNSTransform& DKNSTransform::operator *= (const DKNSTransform& t)
{
this->position = this->position * t.orientation + t.position;
this->orientation *= t.orientation;
return *this;
}
bool DKNSTransform::operator == (const DKNSTransform& t) const
{
return t.orientation == this->orientation && t.position == this->position;
}
bool DKNSTransform::operator != (const DKNSTransform& t) const
{
return t.orientation != this->orientation || t.position != this->position;
}
|
4a4d047c4b45d4e9e77758dc917ab55ef024e7d1
|
d36fb072d0b6861bdcb22d4c102e370e27e7a0da
|
/기초테스트/Mine/Project1/소스.cpp
|
fa12e63291c1eb98a3ab870958ea049a61bcad31
|
[] |
no_license
|
taeyong5th/kimtaeyong
|
9af42d3f9ea7dd1b37c47787684c4eca22fed850
|
8df4f237b6b4018bd262632e08c3f96e8054fc72
|
refs/heads/master
| 2022-04-06T03:30:39.720920
| 2020-03-11T05:19:06
| 2020-03-11T05:19:06
| 200,011,748
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 75
|
cpp
|
소스.cpp
|
#include "GameManager.h"
void main()
{
GameManager game;
game.start();
}
|
c480354c5f09b0eef6e318fbcb47b6f14e9cdd0d
|
702229825d97d28b79c2719e4edc5270a2b54631
|
/game_project/game04/DiploidEngine_DirectX/header/ver2.0/Main/Collision.h
|
3544c58986d41dcec32350519113ca1a9d5ee833
|
[] |
no_license
|
Keioh/DXLib
|
fb10edf15468e6b9094e849a872f6f58d7903eb8
|
b469010bc02b58cfcdcb334fecc28a892ba9579f
|
refs/heads/master
| 2023-02-08T01:57:27.842954
| 2023-01-26T10:59:58
| 2023-01-26T10:59:58
| 91,177,788
| 0
| 0
| null | null | null | null |
SHIFT_JIS
|
C++
| false
| false
| 1,272
|
h
|
Collision.h
|
#pragma once
#include <list>
#include "DxLib.h"
#include "ver2.0/Graphics/DiploidCircleV2.h"
#include "ver2.0/Graphics/DiploidBoxV2.h"
using namespace std;
class DiploidCollision
{
private:
int upadata_count;//いつ更新するかのカウント(画面外など、頻繁に判定をしたくない場所で計算回数を減らすための変数)
int window_size_x = 1280, window_size_y = 720;
protected:
public:
bool CircleAndCircleCollisionUpdate(DiploidCircleV2* circle_one, DiploidCircleV2* circle_two, int updata_rate = 0);//円と円の当たり判定を実行します。(戻り値は二つの円がヒットしていたらtrueを返します。)
VECTOR CircleAndCircleCollisionPointsUpdate(DiploidCircleV2* circle_one, DiploidCircleV2* circle_two, int updata_rate = 0);//円と円が当たった瞬間の位置を得ます。(戻り値は当たった場所の位置を返します。zには半径が入っています。)
bool BoxAndMouseCollisionUpdate(DiploidBoxV2* box, int mouse_x, int mouse_y, int updata_rate = 0);//四角とマウスの当たり判定を実行します。(戻り値はマウスと四角がヒットしていたらtrueを返します。)
int GetUpdateCounter();//更新頻度を数えるカウンターを取得します。
};
|
18fd0acab3afade62850d391790c7a3aeb811ad1
|
1f575f6fd3812e3e053e47be37e8b2866e031eb9
|
/practisePro/isPostOrder.cpp
|
61df9e9946950f8a48df1394a5d56a229501cb3a
|
[] |
no_license
|
cFreee/ATOffer
|
4b147a6b0d4ab985a009f0385585307ab0e2699e
|
e8ae32b5cf17a40286c40fc7e153cd29ce2d07a0
|
refs/heads/master
| 2021-05-11T06:00:01.997734
| 2018-02-28T11:47:29
| 2018-02-28T11:47:29
| 117,976,556
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 649
|
cpp
|
isPostOrder.cpp
|
#include "solution.h"
bool solution::isPostOrder(int *postOrder, int length) {
if (postOrder == NULL || length <= 1) {
return true;
}
bool isPost = true;
int index = 0;
for (int i = 0; i < length - 1; i++) {
if (*(postOrder + length - 1) > *(postOrder + i)) {
index++;
} else {
break;
}
}
for (int i = index; i < length - 1; i++) {
if (*(postOrder + length - 1) > *(postOrder + i)) {
isPost = false;
break;
}
}
return isPost && isPostOrder(postOrder, index) && isPostOrder(postOrder + index, length - 1 - index);
}
|
6fda412e101a69d72c54a3c826a4253b66856516
|
b5225067ae4f2e1bcb0f8f4acbc2290c725066b1
|
/octet/src/examples/example_prototype/shape.h
|
75b7127186ae23913206594f035be5ffbaf63b00
|
[] |
no_license
|
GonLou/Octet
|
70183f56ca3586ea82ea81441ede93d70767ac66
|
ad661757e344f8bfc46b7beaabf339aa5c59cd12
|
refs/heads/master
| 2021-01-13T01:44:40.899849
| 2014-11-09T01:29:41
| 2014-11-09T01:29:41
| 26,076,513
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 3,657
|
h
|
shape.h
|
////////////////////////////////////////////////////////////////////////////////
///
/// Goncalo Lourenco 2014
///
/// Shape Class
///
/// is where all the game objects are registered
namespace octet {
namespace scene {
/// Shape Class
/// game objects
class shape : public resource {
public:
int line; /// keep the number of the vertical lane 1, 2 or 3
int position; /// position of the object
int node; /// the node to control the object
float speed; /// the speed of the object
int time; /// the spawn time of the object
int shape_type; /// indicates the shape type
boolean is_alive; /// display if the object is still to be deployed or still at the screen
int color; /// the color of the object
/// Default Constructor
///
/// where the game objects are initialized
shape(int color, int line, int node, int time, int shape_type) {
this->color = color;
this->line = line;
this->position = 0;
this->node = node;
this->speed = 0.5f;
this->time = time;
this->shape_type = shape_type;
this->is_alive = true;
}
/// Destructor
///
/// where the game objects are destroyed
~shape(void) {
}
/// set the lane of the object : 1 - left, 2 - center, 3 - right,
void set_line(int line) {
this->line = line;
}
/// set the position of the object
void set_position(int pos) {
this->position = pos;
}
/// set the node of the object for control purposes
void set_node(int node) {
this->node = node;
}
/// set the speed of the object
void set_speed(float speed) {
this->speed = speed;
}
/// set the time to spawn the object
void set_time(int time) {
this->time = time;
}
/// set the type of shape
void set_shape_type(int shape_type) {
this->shape_type = shape_type;
}
/// set if the object is still valid or not
void set_is_alive(int is_alive) {
this->is_alive = is_alive;
}
/// set the object color
void set_color(int color) {
this->color = color;
}
/// get the lane of the object
int get_line() {
return this->line;
}
/// get the node of the object for control purposes
int get_node() {
return this->node;
}
/// get the position of the object
int get_position() {
return this->position;
}
/// get the speed of the object
float get_speed() {
return this->speed;
}
/// get the spawn time from the object
int get_time() {
return this->time;
}
/// get the shape type
int get_shape_type() {
return this->shape_type;
}
/// get tha value of the object if still is alive
boolean get_is_alive() {
return this->is_alive;
}
/// get the color of the object
int get_color() {
return this->color;
}
/// move all the game shapes
void move(int node, ref<visual_scene> app_scene) {
scene_node *move = app_scene->get_mesh_instance(node)->get_node();
move->translate(vec3(0.0f, 0.0f, this->get_speed()));
inc_position();
}
/// when a shape is corrected collected deploys a reducer effect
void fade(int node, ref<visual_scene> app_scene) {
scene_node *move = app_scene->get_mesh_instance(node)->get_node();
this->set_speed(5);
move->translate(vec3(0.0f, 0.0f, this->get_speed()));
move->scale(vec3(this->get_speed() / 50, this->get_speed() / 50, this->get_speed() / 50));
inc_position();
}
/// increment object position
void inc_position() {
this->position = this->position + 1;
}
/// decrement object position
void inc_speed() {
this->speed = this->speed + 0.1f;
}
};
}
}
|
3ecf0d8467cba607c9302858172b26417db98691
|
5728c8860cd694743ccb5ca8515cbcf7dbe97ada
|
/src/connection_pool.cpp
|
f313b4fa1f9d65aa7830cdc700305532ec6dc19c
|
[] |
no_license
|
BoxuanXu/Leano
|
2f576c14fec489936e5c14d4f0d296e846729224
|
571ef29d8d613868894be7d1ca89eec97d1edc59
|
refs/heads/master
| 2020-03-11T07:19:09.587054
| 2018-07-04T09:40:08
| 2018-07-04T09:40:08
| 129,853,377
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 4,152
|
cpp
|
connection_pool.cpp
|
/*================================================================
* Copyright (C) 2018 . All rights reserved.
*
* 文件名称:te.h
* 创 建 者: xuboxuan
* 创建日期:2018年03月29日
* 描 述:
*
================================================================*/
#include "include/connection_pool.h"
#include <stdio.h>
#include <exception>
#include <stdexcept>
using namespace std;
using namespace sql;
ConnPool* ConnPool::connPool = NULL;
//连接池的构造函数
ConnPool::ConnPool(string url, string userName, string password, int maxSize) {
this->maxSize = maxSize;
this->curSize = 0;
this->username = userName;
this->password = password;
this->url = url;
try {
this->driver = sql::mysql::get_driver_instance();
} catch (sql::SQLException& e) {
LEANO_LOG_ERROR << "驱动实例出错";
} catch (std::runtime_error& e) {
LEANO_LOG_ERROR << "运行出错了";
}
this->InitConnection(maxSize / 2);
}
//获取连接池对象,单例模式
ConnPool* ConnPool::GetInstance(int maxSize, string url, string user,
string pwd) {
if (connPool == NULL) {
connPool = new ConnPool(url, user, pwd, maxSize);
}
return connPool;
}
//初始化连接池,创建最大连接数的一半连接数量
void ConnPool::InitConnection(int iInitialSize) {
Connection* conn;
pthread_mutex_lock(&lock);
for (int i = 0; i < iInitialSize; i++) {
conn = this->CreateConnection();
if (conn) {
connList.push_back(conn);
++(this->curSize);
} else {
LEANO_LOG_ERROR << "创建CONNECTION出错";
}
}
pthread_mutex_unlock(&lock);
}
//创建连接,返回一个Connection
Connection* ConnPool::CreateConnection() {
Connection* conn;
try {
conn =
driver->connect(this->url, this->username, this->password); //建立连接
return conn;
} catch (sql::SQLException& e) {
LEANO_LOG_ERROR << "创建连接出错";
return NULL;
} catch (std::runtime_error& e) {
LEANO_LOG_ERROR << "运行时出错";
return NULL;
}
}
//在连接池中获得一个连接
Connection* ConnPool::GetConnection() {
Connection* con;
pthread_mutex_lock(&lock);
if (connList.size() > 0) { //连接池容器中还有连接
con = connList.front(); //得到第一个连接
connList.pop_front(); //移除第一个连接
if (con->isClosed()) { //如果连接已经被关闭,删除后重新建立一个
delete con;
con = this->CreateConnection();
}
//如果连接为空,则创建连接出错
if (con == NULL) {
--curSize;
}
pthread_mutex_unlock(&lock);
return con;
} else {
if (curSize < maxSize) { //还可以创建新的连接
con = this->CreateConnection();
if (con) {
++curSize;
pthread_mutex_unlock(&lock);
return con;
} else {
pthread_mutex_unlock(&lock);
return NULL;
}
} else { //建立的连接数已经达到maxSize
pthread_mutex_unlock(&lock);
return NULL;
}
}
}
//回收数据库连接
void ConnPool::ReleaseConnection(sql::Connection* conn) {
if (conn) {
pthread_mutex_lock(&lock);
connList.push_back(conn);
pthread_mutex_unlock(&lock);
}
}
//连接池的析构函数
ConnPool::~ConnPool() { this->DestoryConnPool(); }
//销毁连接池,首先要先销毁连接池的中连接
//存在的问题?如果有不在连接池的其它连接在运行怎么办销毁?是否需要另外一个list记录正在运行的连接?
void ConnPool::DestoryConnPool() {
list<Connection*>::iterator icon;
pthread_mutex_lock(&lock);
for (icon = connList.begin(); icon != connList.end(); ++icon) {
this->DestoryConnection(*icon); //销毁连接池中的连接
}
curSize = 0;
connList.clear(); //清空连接池中的连接
pthread_mutex_unlock(&lock);
}
//销毁一个连接
void ConnPool::DestoryConnection(Connection* conn) {
if (conn) {
try {
conn->close();
} catch (sql::SQLException& e) {
perror(e.what());
} catch (std::exception& e) {
perror(e.what());
}
delete conn;
}
}
|
c4e941afb347e7959203480104ab228ae4ca7dbe
|
971aa16cc48bdd1be6d7fa14bdd22dc7fec644c3
|
/file_handling.cpp
|
7a3bdd36ca013a02cd011811b27cbb695999dae3
|
[] |
no_license
|
Kush22/Text-Editor
|
b1c64f13508f442176e18e0215adc4bb8c237dbe
|
ef1ac1efd38bbebea9aefecf4e94023aa06e1925
|
refs/heads/master
| 2021-01-19T14:00:20.267295
| 2018-02-19T18:06:36
| 2018-02-19T18:06:36
| 100,874,541
| 1
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,638
|
cpp
|
file_handling.cpp
|
/**
* Code By: Kushagra Gupta
* Roll Number: 20172079
* Subject: M17CSE531: Operating System- Assignment Sumbission
**/
#ifndef FILE_HANDLING_H
#define FILE_HANDLING_H
#include "editorLibrary.h"
#include <cmath>
// list< string > backgroundFile;
list< string > :: iterator it;
//list< string > :: iterator terminal_begin;
list< string > :: iterator terminal_end;
list< string > buffer;
int beginningPosition = 0;
void refreshScreen(){
clearTerminalScreen();
moveCursorXY(1,1);
int i = 1;
int j = 0;
moveCursorXY(1,1);
for(it = terminal_begin; it != backgroundFile.end() && i <= editor.terminal_rows-2; i++){
string line = (*it).substr(j*editor.terminal_cols, editor.terminal_cols);
j++;
cout << line;
cout.flush();
if(line[line.length()-1] == '\n'){
it++;
j = 0;
}
}
//moveCursorXY(1,1);
drawStatusBar();
}
void initialiseScreenWithFile(string file_name){
if(terminalSize(&editor.terminal_rows, &editor.terminal_cols) == -1)
error("Error in Getting Window Size");
string line;
ifstream inputFile(file_name);
drawStatusBar();
//initialise the data structure with the contents of the file
if(inputFile.is_open()){
while(getline(inputFile, line)){
line = line + "\n";
backgroundFile.push_back(line);
}
/*if(backgroundFile.size() == 0){
backgroundFile.push_back("");
}*/
terminal_begin = backgroundFile.begin();
line_number = terminal_begin;
refreshScreen();
inputFile.close();
moveCursorXY(1,1);
}
else{
cout << "Unable to open file!";
cout.flush();
char ch = getCharInput();
system("tput rmcup");
disableRawMode();
exit(0);
}
}
#endif
|
21ae859166ec30d94b8e0321ec5cd6aad11069de
|
7eb74893776632c04c729053369bec5b6bad73fd
|
/DFS/Sum_of_Nodes_with_Even-Valued_Grandparent.cpp
|
d7a927047f64e81da291b517fe796f976205223a
|
[] |
no_license
|
Krish03na/Leetcode-solutions
|
ce5d2c6ad4367beebc23843ee62369895a181a80
|
80c5d6a9aafbabd9cf67db319941f6ba408b277f
|
refs/heads/main
| 2023-02-21T07:34:47.116741
| 2021-01-18T15:49:25
| 2021-01-18T15:49:25
| 324,298,775
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,279
|
cpp
|
Sum_of_Nodes_with_Even-Valued_Grandparent.cpp
|
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
int sumEvenGrandparent(TreeNode* root) {
//sol1
// if(!root) return 0;
// int s=0;
// if(root->val%2==0){
// if(root->left){
// if(root->left->left) s+=root->left->left->val;
// if(root->left->right) s+=root->left->right->val;
// }
// if(root->right){
// if(root->right->left) s+=root->right->left->val;
// if(root->right->right) s+=root->right->right->val;
// }
// }
// return s+sumEvenGrandparent(root->left)+sumEvenGrandparent(root->right);
//bfs
int ans=0;
if(root){
queue<TreeNode*>q;
q.push(root);
while(!q.empty()){
TreeNode*temp=q.front();
q.pop();
if(temp->left){
q.push(temp->left);
if(temp->val%2==0){
if(temp->left->left){
ans+=temp->left->left->val;
}
if(temp->left->right){
ans+=temp->left->right->val;
}
}
}
if(temp->right){
q.push(temp->right);
if(temp->val%2==0){
if(temp->right->left){
ans+=temp->right->left->val;
}
if(temp->right->right){
ans+=temp->right->right->val;
}
}
}
}
}
return ans;
}
};
|
c3b11e23cae791cb88367c15910306e5430a91a7
|
9abad0a571ca9967134c1c6d5741eb8572c1e135
|
/Node.cpp
|
3ebd14bbfa61d732ef03f337c39af173ee8355e6
|
[
"MIT"
] |
permissive
|
sthairno/S3DNodeEditor
|
84bce60ab4892ccf4ef6cec6f8cceb1369216f1f
|
150a42f4687adb07e85c53c7cc707651502a9974
|
refs/heads/master
| 2023-01-04T11:05:18.275207
| 2020-10-26T03:26:28
| 2020-10-26T03:26:28
| 287,414,531
| 7
| 0
|
MIT
| 2020-10-26T03:26:29
| 2020-08-14T01:22:45
|
C++
|
UTF-8
|
C++
| false
| false
| 12,255
|
cpp
|
Node.cpp
|
#include "Node.hpp"
Triangle EquilateralTriangle(const Vec2& center, const double& r, const double& theta)
{
return Triangle(Circular(r, theta), Circular(r, theta + 120_deg), Circular(r, theta + 240_deg))
.setCentroid(center);
}
void NodeEditor::Node::calcSize(const Config& cfg)
{
m_size.y = Max(m_inputSockets.size() + m_prevNodeSockets.size(), m_outputSockets.size() + m_nextNodeSockets.size()) * cfg.font.height() + cfg.TitleHeight + cfg.RectR + ChildSize.y;
float inWidthMax = 0, outWidthMax = 0;
for (auto& prevSocket : m_prevNodeSockets)
{
const float width = static_cast<float>(cfg.font(prevSocket->Name).region().w);
if (width > inWidthMax)
{
inWidthMax = width;
}
}
for (auto& inSocket : m_inputSockets)
{
const auto tex = cfg.getTypeIcon(inSocket->ValueType);
const float width = static_cast<float>(cfg.font(inSocket->Name).region().w + (tex ? tex->width() : 0));
if (width > inWidthMax)
{
inWidthMax = width;
}
}
for (auto& nextSocket : m_nextNodeSockets)
{
const float width = static_cast<float>(cfg.font(nextSocket->Name).region().w);
if (width > outWidthMax)
{
outWidthMax = width;
}
}
for (auto& outSocket : m_outputSockets)
{
const auto tex = cfg.getTypeIcon(outSocket->ValueType);
const float width = static_cast<float>(cfg.font(outSocket->Name).region().w + (tex ? tex->width() : 0));
if (width > outWidthMax)
{
outWidthMax = width;
}
}
m_size.x = Max<float>({ cfg.WidthMin, inWidthMax + cfg.IOMargin + outWidthMax, (float)ChildSize.x });
}
void NodeEditor::Node::calcRect(const Config& cfg)
{
m_rect = RectF(Location, m_size);
{
m_titleRect = RectF(Location, m_size.x, cfg.TitleHeight);
m_contentRect = RectF(m_rect.x, m_rect.y + cfg.TitleHeight, m_rect.w, m_rect.h - cfg.TitleHeight - cfg.RectR);
{
m_socketRect = RectF(m_contentRect.pos, m_contentRect.w, Max(m_inputSockets.size() + m_prevNodeSockets.size(), m_outputSockets.size() + m_nextNodeSockets.size()) * cfg.font.height());
m_childRect = RectF(Arg::topCenter = m_socketRect.bottomCenter() + Vec2(0, 1), ChildSize);
}
}
}
void NodeEditor::Node::drawBackground(const Config& cfg)
{
double s = 0;
const auto& roundRect = m_rect.rounded(cfg.RectR);
if (m_backColStw.elapsed() < 1s)
{
s = (1 - m_backColStw.elapsed() / 1s) * 0.8;
}
//四角の描画
roundRect.draw(HSV(m_backHue, s, 0.7));
if (Selecting)
{
roundRect.drawFrame(0, 2, Palette::Orange);
}
m_contentRect.draw(ColorF(0.9));
//タイトルの描画
cfg.font(Name).drawAt(m_titleRect.center(), Palette::Black);
}
void NodeEditor::Node::setBackCol(const double hue)
{
m_backColStw.restart();
m_backHue = hue;
}
void NodeEditor::Node::cfgInputSockets(Array<std::pair<Type, String>> cfg)
{
m_inputSockets = Array<std::shared_ptr<ValueSocket>>(cfg.size());
for (size_t i = 0; i < cfg.size(); i++)
{
m_inputSockets[i] = std::make_shared<ValueSocket>(*this, cfg[i].second, IOType::Input, i, cfg[i].first);
}
}
void NodeEditor::Node::cfgOutputSockets(Array<std::pair<Type, String>> cfg)
{
m_outputSockets = Array<std::shared_ptr<ValueSocket>>(cfg.size());
for (size_t i = 0; i < cfg.size(); i++)
{
m_outputSockets[i] = std::make_shared<ValueSocket>(*this, cfg[i].second, IOType::Output, i, cfg[i].first);
}
}
void NodeEditor::Node::cfgPrevExecSocket(const Array<String>& names)
{
m_prevNodeSockets = Array<std::shared_ptr<ExecSocket>>(names.size());
for (size_t i = 0; i < names.size(); i++)
{
m_prevNodeSockets[i] = std::make_shared<ExecSocket>(*this, names[i], IOType::Input, i);
}
}
void NodeEditor::Node::cfgNextExecSocket(const Array<String>& names)
{
m_nextNodeSockets = Array<std::shared_ptr<ExecSocket>>(names.size());
for (size_t i = 0; i < names.size(); i++)
{
m_nextNodeSockets[i] = std::make_shared<ExecSocket>(*this, names[i], IOType::Output, i);
}
}
void NodeEditor::Node::run()
{
m_errorMsg.reset();
try
{
for (auto& inSocket : m_inputSockets)
{
if (!inSocket->ConnectedSocket)
{
throw Error(U"ノード名:\"{}\", \"入力ソケット:\"{}\"のノードが指定されていません"_fmt(Name, inSocket->Name));
}
inSocket->ConnectedSocket[0]->Parent.run();
inSocket->setValue(dynamic_pointer_cast<ValueSocket>(inSocket->ConnectedSocket[0])->value());
}
setBackCol(220);
childRun();
for (auto& outSocket : m_outputSockets)
{
if (!outSocket->value().has_value())
{
throw Error(U"ノード名:\"{}\", \"出力ソケット:\"{}\"の出力が指定されていません"_fmt(Name, outSocket->Name));
}
}
//次のノードを実行
if (m_nextNodeSockets)
{
for (auto& nextSocket : m_nextNodeSockets[NextExecIdx]->ConnectedSocket)
{
nextSocket->Parent.run();
}
}
}
catch (Error& ex)
{
setBackCol(20);
m_errorMsg = ex.what();
}
}
void NodeEditor::Node::update(const Config& cfg, Input& input)
{
calcSize(cfg);
if (m_isGrab)
{
if (MouseL.pressed())
{
Location += Cursor::DeltaF();
Cursor::RequestStyle(CursorStyle::Hand);
}
else
{
m_isGrab = false;
}
}
calcRect(cfg);
if (input.mouseOver(m_titleRect))
{
Cursor::RequestStyle(CursorStyle::Hand);
if (input.leftClicked(m_titleRect))
{
m_isGrab = true;
}
}
if (ChildSize != SizeF(0, 0))
{
const Transformer2D transform(Mat3x2::Translate(m_childRect.pos), true);
childUpdate(cfg, input);
}
m_clicked = !m_isGrab && input.leftClicked(m_rect);
}
void NodeEditor::Node::draw(const Config& cfg)
{
drawBackground(cfg);
//エラーメッセージの吹き出し描画
if (m_errorMsg)
{
const auto bottomCenter = m_rect.topCenter();
const auto text = cfg.font(m_errorMsg.value());
const auto topCenter = bottomCenter - Vec2(0, 10);
const RectF balloonRect(Arg::bottomCenter = topCenter, text.region().size + SizeF(20, 0));
balloonRect.draw(Palette::White);
Triangle(topCenter - Vec2(5, 0), topCenter + Vec2(5, 0), bottomCenter).draw(Palette::White);
text.drawAt(balloonRect.center(), Palette::Black);
}
//ノードの描画
Vec2 fontBasePos = m_contentRect.tl();
for (auto& prevSocket : m_prevNodeSockets)
{
auto pos = prevSocket->calcPos(cfg);
auto triangle = EquilateralTriangle(pos, cfg.ConnectorSize / 2, 90_deg);
cfg.font(prevSocket->Name).draw(Arg::topLeft = fontBasePos, Palette::Black);
fontBasePos.y += cfg.font.height();
if (prevSocket->ConnectedSocket)
{
triangle.draw(Palette::White);
}
else
{
triangle.drawFrame(1, Palette::White);
}
}
for (int i = 0; i < m_inputSockets.size(); i++)
{
auto& inSocket = m_inputSockets[i];
const auto tex = cfg.getTypeIcon(inSocket->ValueType);
const Vec2 fontPos = fontBasePos + Vec2(0, cfg.font.height() * i) + Vec2(tex ? tex->width() : 0, 0);
auto fontlc = cfg.font(inSocket->Name).draw(Arg::topLeft = fontPos, Palette::Black).leftCenter();
if (tex)
{
tex->draw(Arg::rightCenter = fontlc);
}
auto pos = inSocket->calcPos(cfg);
auto circle = Circle(pos, cfg.ConnectorSize / 2);
if (inSocket->ConnectedSocket)
{
circle.draw(Palette::White);
}
else
{
circle.drawFrame(1, Palette::White);
}
}
fontBasePos = m_contentRect.tr();
for (auto& nextSocket : m_nextNodeSockets)
{
auto pos = nextSocket->calcPos(cfg);
auto triangle = EquilateralTriangle(pos, cfg.ConnectorSize / 2, 90_deg);
cfg.font(nextSocket->Name).draw(Arg::topRight = fontBasePos, Palette::Black);
fontBasePos.y += cfg.font.height();
if (nextSocket->ConnectedSocket)
{
triangle.draw(Palette::White);
}
else
{
triangle.drawFrame(1, Palette::White);
}
}
for (int i = 0; i < m_outputSockets.size(); i++)
{
auto& outSocket = m_outputSockets[i];
const auto tex = cfg.getTypeIcon(outSocket->ValueType);
const Vec2 fontPos = fontBasePos + Vec2(0, cfg.font.height() * i) - Vec2(tex ? tex->width() : 0, 0);
cfg.font(outSocket->Name).draw(Arg::topRight = fontPos, Palette::Black);
if (tex)
{
tex->draw(Arg::leftCenter = Vec2(fontPos.x, fontPos.y + cfg.font.height() / 2));
}
auto circle = Circle(outSocket->calcPos(cfg), cfg.ConnectorSize / 2);
if (outSocket->ConnectedSocket)
{
circle.draw(Palette::White);
}
else
{
circle.drawFrame(1, Palette::White);
}
}
//子要素の描画
if (ChildSize != SizeF(0, 0))
{
const Transformer2D transform(Mat3x2::Translate(m_childRect.pos), true);
childDraw(cfg);
}
}
NodeEditor::Node::~Node()
{
disconnectAllSockets();
}
void NodeEditor::Node::disconnectAllSockets()
{
for (auto& socket : m_inputSockets)
{
ISocket::disconnect(socket);
}
for (auto& socket : m_outputSockets)
{
ISocket::disconnect(socket);
}
for (auto& socket : m_prevNodeSockets)
{
ISocket::disconnect(socket);
}
for (auto& socket : m_nextNodeSockets)
{
ISocket::disconnect(socket);
}
}
void NodeEditor::Node::serialize(JSONWriter& writer) const
{
writer.startObject();
{
writer.key(U"id").write(ID);
writer.key(U"class").write(Class);
writer.key(U"location").write(Location);
writer.key(U"inputSockets").startArray();
{
for (const auto& socket : m_inputSockets)
{
socket->serialize(writer);
}
}
writer.endArray();
writer.key(U"outputSockets").startArray();
{
for (const auto& socket : m_outputSockets)
{
socket->serialize(writer);
}
}
writer.endArray();
writer.key(U"prevNodeSockets").startArray();
{
for (const auto& socket : m_prevNodeSockets)
{
socket->serialize(writer);
}
}
writer.endArray();
writer.key(U"nextNodeSockets").startArray();
{
for (const auto& socket : m_nextNodeSockets)
{
socket->serialize(writer);
}
}
writer.endArray();
writer.key(U"child");
childSerialize(writer);
}
writer.endObject();
}
void NodeEditor::Node::deserialize(const JSONValue& json)
{
ID = json[U"id"].get<decltype(ID)>();
Location = json[U"location"].get<decltype(Location)>();
childDeserialize(json[U"child"]);
}
void NodeEditor::Node::deserializeSockets(const JSONValue& json, Array<std::shared_ptr<Node>>& nodes)
{
for (const auto& socketJson : json[U"inputSockets"].arrayView())
{
auto index = socketJson[U"index"].get<size_t>();
auto socket = m_inputSockets[index];
ISocket::disconnect(socket);
for (const auto& connectedSocket : socketJson[U"connectedSocket"].arrayView())
{
auto nodeID = connectedSocket[U"nodeID"].get<decltype(ID)>();
auto socketIndex = connectedSocket[U"socketIndex"].get<size_t>();
for (auto& node : nodes)
{
if (node->ID == nodeID)
{
ISocket::connect(socket, node->m_outputSockets[socketIndex]);
}
}
}
}
for (const auto& socketJson : json[U"outputSockets"].arrayView())
{
auto index = socketJson[U"index"].get<size_t>();
auto socket = m_outputSockets[index];
ISocket::disconnect(socket);
for (const auto& connectedSocket : socketJson[U"connectedSocket"].arrayView())
{
auto nodeID = connectedSocket[U"nodeID"].get<decltype(ID)>();
auto socketIndex = connectedSocket[U"socketIndex"].get<size_t>();
for (auto& node : nodes)
{
if (node->ID == nodeID)
{
ISocket::connect(socket, node->m_inputSockets[socketIndex]);
}
}
}
}
for (const auto& socketJson : json[U"prevNodeSockets"].arrayView())
{
auto index = socketJson[U"index"].get<size_t>();
auto socket = m_prevNodeSockets[index];
ISocket::disconnect(socket);
for (const auto& connectedSocket : socketJson[U"connectedSocket"].arrayView())
{
auto nodeID = connectedSocket[U"nodeID"].get<decltype(ID)>();
auto socketIndex = connectedSocket[U"socketIndex"].get<size_t>();
for (auto& node : nodes)
{
if (node->ID == nodeID)
{
ISocket::connect(socket, node->m_nextNodeSockets[socketIndex]);
}
}
}
}
for (const auto& socketJson : json[U"nextNodeSockets"].arrayView())
{
auto index = socketJson[U"index"].get<size_t>();
auto socket = m_nextNodeSockets[index];
ISocket::disconnect(socket);
for (const auto& connectedSocket : socketJson[U"connectedSocket"].arrayView())
{
auto nodeID = connectedSocket[U"nodeID"].get<decltype(ID)>();
auto socketIndex = connectedSocket[U"socketIndex"].get<size_t>();
for (auto& node : nodes)
{
if (node->ID == nodeID)
{
ISocket::connect(socket, node->m_prevNodeSockets[socketIndex]);
}
}
}
}
}
|
d51f2ca8844dfd674f0066e04c1a18918c9c61b0
|
3d3be59222796e8bbedc160c1f1595b245bde002
|
/OpenGl7/OpenGL/OpenGL/material.cpp
|
ed24b1b88385c81334860696e976a37b4605efce
|
[
"MIT"
] |
permissive
|
coconutjim/hseb4-compgraph
|
77fc8a04345f32e840f5bd19bebdeef7cd0f20c0
|
2d4d883873b3589d7dceeef3597eda185c368ef2
|
refs/heads/master
| 2022-07-22T03:29:37.325022
| 2022-07-14T19:34:28
| 2022-07-14T19:34:28
| 234,436,864
| 1
| 0
| null | null | null | null |
WINDOWS-1251
|
C++
| false
| false
| 1,874
|
cpp
|
material.cpp
|
/*
Осипов Лев Игоревич
Проект 18. OpenGL7
Visual Studio 2013
20.03.2016
Сделано:
1) на сцену добавлены объекты - дом, сундук и 3 Дедпула
2) у всех объектов можно посмотреть нормали
3) кроме существующей системы частиц, добавлено еще 3 дополнительных системы (под Дедпулами). Они имеют разные параметры,
средняя имитирует пламя
4) параметры существующей системы частиц выводятся на сцену и изменяются с помощью клавиш (клавиши управления см. на сцене)
5) можно изменить скорость вращения объекта (клавиши управления см. на сцене)
6) вся информация об управлении и об авторе программе вынесена на сцену
7) код закомментирован
*/
#include "common_header.h"
#include "material.h"
CMaterial::CMaterial()
{
fSpecularIntensity = 1.0f;
fSpecularPower = 32.0f;
}
CMaterial::CMaterial(float a_fSpecularIntensity, float a_fSpecularPower)
{
fSpecularIntensity = a_fSpecularIntensity;
fSpecularPower = a_fSpecularPower;
}
/*-----------------------------------------------
Name: SetUniformData
Params: spProgram - shader program
sMaterialVarName - name of material variable
Result: Sets all material uniform data.
/*---------------------------------------------*/
void CMaterial::SetUniformData(CShaderProgram* spProgram, string sMaterialVarName)
{
spProgram->SetUniform(sMaterialVarName+".fSpecularIntensity", fSpecularIntensity);
spProgram->SetUniform(sMaterialVarName+".fSpecularPower", fSpecularPower);
}
|
41497514c3084421eafbcc205a8a1e81c4de6b7e
|
749a2467fafe4ff353af2eafcc3aa77e8fc3ada7
|
/test/editor_test.cpp
|
e65baf7b12071f21c4e2229a1f3375014df42bec
|
[
"MIT"
] |
permissive
|
BehaviorTree/Groot
|
81456eb2bf99e20e2fe58e70d1fb05b5ec5fa340
|
f7fac396eaf84efa8eab8a91f335e343ec8ce25f
|
refs/heads/master
| 2023-07-13T14:24:09.650749
| 2023-06-09T15:37:28
| 2023-06-09T15:37:28
| 137,749,316
| 642
| 233
| null | 2023-06-09T15:37:29
| 2018-06-18T12:31:25
|
C++
|
UTF-8
|
C++
| false
| false
| 20,032
|
cpp
|
editor_test.cpp
|
#include "groot_test_base.h"
#include "bt_editor/sidepanel_editor.h"
#include <QAction>
#include <QLineEdit>
class EditorTest : public GrootTestBase
{
Q_OBJECT
public:
EditorTest() {}
~EditorTest() {}
private slots:
void initTestCase();
void cleanupTestCase();
void renameTabs();
void loadFile();
void loadFailed();
void savedFileSameAsOriginal();
void undoRedo();
void testSubtree();
void modifyCustomModel();
void multipleSubtrees();
void editText();
void loadModelLess();
void longNames();
void clearModels();
void undoWithSubtreeExpanded();
};
void EditorTest::initTestCase()
{
main_win = new MainWindow(GraphicMode::EDITOR, nullptr);
main_win->resize(1200, 800);
main_win->show();
}
void EditorTest::cleanupTestCase()
{
QApplication::processEvents();
sleepAndRefresh( 1000 );
main_win->on_actionClear_triggered();
main_win->close();
}
void EditorTest::loadFile()
{
QString file_xml = readFile(":/crossdoor_with_subtree.xml");
main_win->on_actionClear_triggered();
main_win->loadFromXML( file_xml );
QString saved_xml = main_win->saveToXML();
QFile qFile("crossdoor_EditorTest_loadFile.xml");
if (qFile.open(QIODevice::WriteOnly))
{
QTextStream out(&qFile); out << saved_xml;
qFile.close();
}
sleepAndRefresh( 500 );
//-------------------------------
// Compare AbsBehaviorTree
main_win->on_actionClear_triggered();
main_win->loadFromXML( file_xml );
auto tree_A1 = getAbstractTree("MainTree");
auto tree_A2 = getAbstractTree("DoorClosed");
main_win->loadFromXML( saved_xml );
auto tree_B1 = getAbstractTree("MainTree");
auto tree_B2 = getAbstractTree("DoorClosed");
bool same_maintree = (tree_A1 == tree_B1);
if( !same_maintree )
{
tree_A1.debugPrint();
tree_B1.debugPrint();
}
QVERIFY2( same_maintree, "AbsBehaviorTree comparison fails" );
QVERIFY2( file_xml.simplified() == saved_xml.simplified(),
"Loaded and saved XML are not the same" );
bool same_doorclosed = tree_A2 == tree_B2;
if( !same_doorclosed )
{
tree_A2.debugPrint();
tree_B2.debugPrint();
}
QVERIFY2( same_doorclosed, "AbsBehaviorTree comparison fails" );
//-------------------------------
// Next: expand the Subtree [DoorClosed]
auto tree = getAbstractTree("MainTree");
auto subtree_abs_node = tree.findFirstNode("DoorClosed");
QVERIFY2(subtree_abs_node, "Can't find node with ID [DoorClosed]");
{
auto data_model = subtree_abs_node->graphic_node->nodeDataModel();
auto subtree_model = dynamic_cast<SubtreeNodeModel*>(data_model);
QVERIFY2(subtree_model, "Node [DoorClosed] is not SubtreeNodeModel");
QTest::mouseClick( subtree_model->expandButton(), Qt::LeftButton );
}
sleepAndRefresh( 500 );
//---------------------------------
// Expanded tree should save the same file
QString saved_xml_expanded = main_win->saveToXML();
QVERIFY2( saved_xml_expanded.simplified() == saved_xml.simplified(),
"Loaded and saved XMl are not the same" );
//-------------------------------
// Next: collapse again Subtree [DoorClosed]
tree = getAbstractTree("MainTree");
subtree_abs_node = tree.findFirstNode("DoorClosed");
QVERIFY2(subtree_abs_node, "Can't find node with ID [DoorClosed]");
{
auto data_model = subtree_abs_node->graphic_node->nodeDataModel();
auto subtree_model = dynamic_cast<SubtreeNodeModel*>(data_model);
QVERIFY2(subtree_model, "Node [DoorClosed] is not SubtreeNodeModel");
QTest::mouseClick( subtree_model->expandButton(), Qt::LeftButton );
}
sleepAndRefresh( 500 );
}
void EditorTest::savedFileSameAsOriginal()
{
QString file_xml = readFile(":/test_xml_key_reordering_issue.xml");
main_win->on_actionClear_triggered();
main_win->loadFromXML( file_xml );
QString saved_xml = main_win->saveToXML();
QFile qFile("crossdoor_EditorTest_savedFileSameAsOriginal.xml");
if (qFile.open(QIODevice::WriteOnly))
{
QTextStream out(&qFile);
out << saved_xml;
qFile.close();
}
sleepAndRefresh( 500 );
//-------------------------------
// Compare AbsBehaviorTree
main_win->on_actionClear_triggered();
main_win->loadFromXML( file_xml );
auto tree_A1 = getAbstractTree("BehaviorTree");
auto tree_A2 = getAbstractTree("RunPlannerSubtree");
auto tree_A3 = getAbstractTree("ExecutePath");
main_win->loadFromXML( saved_xml );
auto tree_B1 = getAbstractTree("BehaviorTree");
auto tree_B2 = getAbstractTree("RunPlannerSubtree");
auto tree_B3 = getAbstractTree("ExecutePath");
bool same_maintree = (tree_A1 == tree_B1);
if( !same_maintree )
{
tree_A1.debugPrint();
tree_B1.debugPrint();
}
QVERIFY2( same_maintree, "AbsBehaviorTree comparison fails" );
bool same_runplanner = tree_A2 == tree_B2;
if( !same_runplanner )
{
tree_A2.debugPrint();
tree_B2.debugPrint();
}
QVERIFY2( same_runplanner, "AbsBehaviorTree comparison fails" );
bool same_executepath = tree_A2 == tree_B2;
if( !same_executepath )
{
tree_A3.debugPrint();
tree_B3.debugPrint();
}
QVERIFY2( same_executepath, "AbsBehaviorTree comparison fails" );
//-------------------------------
// Compare original and save file contents
QVERIFY2( file_xml.simplified() == saved_xml.simplified(),
"Loaded and saved XML are not the same" );
}
void EditorTest::loadFailed()
{
QString file_xml = readFile(":/crossdoor_with_subtree.xml");
main_win->on_actionClear_triggered();
main_win->loadFromXML( file_xml );
auto tree_A1 = getAbstractTree("MainTree");
auto tree_A2 = getAbstractTree("DoorClosed");
// try to load a bad one
file_xml = readFile(":/issue_3.xml");
testMessageBox(400, TEST_LOCATION(), [&]()
{
// should fail
main_win->loadFromXML( file_xml );
});
// nothing should change!
auto tree_B1 = getAbstractTree("MainTree");
auto tree_B2 = getAbstractTree("DoorClosed");
QVERIFY2( tree_A1 == tree_B1, "AbsBehaviorTree comparison fails" );
QVERIFY2( tree_A2 == tree_B2, "AbsBehaviorTree comparison fails" );
}
void EditorTest::undoRedo()
{
QString file_xml = readFile(":/show_all.xml");
main_win->on_actionClear_triggered();
main_win->loadFromXML( file_xml );
//------------------------------------------
AbsBehaviorTree abs_tree_A, abs_tree_B;
{
auto container = main_win->currentTabInfo();
auto view = container->view();
abs_tree_A = getAbstractTree();
sleepAndRefresh( 500 );
auto pippo_node = abs_tree_A.findFirstNode("Pippo");
auto gui_node = pippo_node->graphic_node;
QPoint pippo_screen_pos = view->mapFromScene(pippo_node->pos);
const QPoint pos_offset(100,0);
QTest::mouseClick( view->viewport(), Qt::LeftButton, Qt::NoModifier, pippo_screen_pos );
QVERIFY2( gui_node->nodeGraphicsObject().isSelected(), "Pippo is not selected");
auto old_pos = view->mapFromScene( container->scene()->getNodePosition( *gui_node ) );
testDragObject(view, pippo_screen_pos, pos_offset);
QPoint new_pos = view->mapFromScene( container->scene()->getNodePosition( *gui_node ) );
QCOMPARE( old_pos + pos_offset, new_pos);
sleepAndRefresh( 500 );
}
//---------- test undo ----------
{
abs_tree_B = getAbstractTree();
main_win->onUndoInvoked();
sleepAndRefresh( 500 );
QCOMPARE( abs_tree_A, getAbstractTree() );
sleepAndRefresh( 500 );
}
{
main_win->onUndoInvoked();
sleepAndRefresh( 500 );
auto empty_abs_tree = getAbstractTree();
QCOMPARE( empty_abs_tree.nodesCount(), size_t(1) );
// nothing should happen
main_win->onUndoInvoked();
main_win->onUndoInvoked();
main_win->onUndoInvoked();
}
{
main_win->onRedoInvoked();
sleepAndRefresh( 500 );
QCOMPARE( getAbstractTree(), abs_tree_A);
main_win->onRedoInvoked();
sleepAndRefresh( 500 );
QCOMPARE( getAbstractTree(), abs_tree_B);
// nothing should happen
main_win->onRedoInvoked();
main_win->onRedoInvoked();
main_win->onRedoInvoked();
}
{
auto container = main_win->currentTabInfo();
auto view = container->view();
auto prev_tree = getAbstractTree();
size_t prev_node_count = prev_tree.nodesCount();
auto node = prev_tree.findFirstNode( "DoSequenceStar" );
QPoint pos = view->mapFromScene(node->pos);
testMouseEvent(view, QEvent::MouseButtonDblClick, pos , Qt::LeftButton);
sleepAndRefresh( 500 );
QTest::keyPress( view->viewport(), Qt::Key_Delete, Qt::NoModifier );
sleepAndRefresh( 500 );
auto smaller_tree = getAbstractTree();
QCOMPARE( prev_node_count - 4 , smaller_tree.nodesCount() );
main_win->onUndoInvoked();
sleepAndRefresh( 500 );
auto undo_tree = getAbstractTree();
size_t undo_node_count = main_win->currentTabInfo()->scene()->nodes().size();
QCOMPARE( prev_node_count , undo_node_count );
QCOMPARE( prev_tree, undo_tree);
main_win->onRedoInvoked();
auto redo_tree = getAbstractTree();
sleepAndRefresh( 500 );
QCOMPARE( smaller_tree, redo_tree);
}
sleepAndRefresh( 500 );
}
void EditorTest::renameTabs()
{
QString file_xml = readFile(":/crossdoor_with_subtree.xml");
main_win->on_actionClear_triggered();
main_win->loadFromXML( file_xml );
testMessageBox(500, TEST_LOCATION(), [&]()
{
// Two tabs with same name would exist
main_win->onTabRenameRequested( 0 , "DoorClosed" );
});
testMessageBox(500, TEST_LOCATION(), [&]()
{
// Two tabs with same name would exist
main_win->onTabRenameRequested( 1 , "MainTree" );
});
main_win->onTabRenameRequested( 0 , "MainTree2" );
main_win->onTabRenameRequested( 1 , "DoorClosed2" );
QVERIFY( main_win->getTabByName("MainTree") == nullptr);
QVERIFY( main_win->getTabByName("DoorClosed") == nullptr);
QVERIFY( main_win->getTabByName("MainTree2") != nullptr);
QVERIFY( main_win->getTabByName("DoorClosed2") != nullptr);
sleepAndRefresh( 500 );
}
void EditorTest::testSubtree()
{
QString file_xml = readFile(":/crossdoor_with_subtree.xml");
main_win->on_actionClear_triggered();
main_win->loadFromXML( file_xml );
auto main_tree = getAbstractTree("MainTree");
auto closed_tree = getAbstractTree("DoorClosed");
auto subtree_abs_node = main_tree.findFirstNode("DoorClosed");
auto data_model = subtree_abs_node->graphic_node->nodeDataModel();
auto subtree_model = dynamic_cast<SubtreeNodeModel*>(data_model);
QTest::mouseClick( subtree_model->expandButton(), Qt::LeftButton );
QAbstractButton *button_lock = main_win->findChild<QAbstractButton*>("buttonLock");
QVERIFY2(button_lock != nullptr, "Can't find the object [buttonLock]");
button_lock->setChecked(false);
QTreeWidget* treeWidget = main_win->findChild<QTreeWidget*>("paletteTreeWidget");
QVERIFY2(treeWidget != nullptr, "Can't find the object [paletteTreeWidget]");
auto subtree_items = treeWidget->findItems("DoorClosed", Qt::MatchExactly | Qt::MatchRecursive);
sleepAndRefresh( 500 );
QCOMPARE(subtree_items.size(), 1);
sleepAndRefresh( 500 );
auto sidepanel_editor = main_win->findChild<SidepanelEditor*>("SidepanelEditor");
sidepanel_editor->onRemoveModel("DoorClosed");
sleepAndRefresh( 500 );
auto tree_after_remove = getAbstractTree("MainTree");
auto fallback_node = tree_after_remove.findFirstNode("root_Fallback");
QCOMPARE(fallback_node->children_index.size(), size_t(3) );
QVERIFY2( main_win->getTabByName("DoorClosed") == nullptr, "Tab DoorClosed not deleted");
sleepAndRefresh( 500 );
//---------------------------------------
// create again the subtree
auto closed_sequence_node = tree_after_remove.findFirstNode("door_closed_sequence");
auto container = main_win->currentTabInfo();
// This must fail and create a MessageBox
testMessageBox(1000, TEST_LOCATION(), [&]()
{
container->createSubtree( *closed_sequence_node->graphic_node, "MainTree" );
});
container->createSubtree( *closed_sequence_node->graphic_node, "DoorClosed" );
sleepAndRefresh( 500 );
auto new_main_tree = getAbstractTree("MainTree");
auto new_closed_tree = getAbstractTree("DoorClosed");
bool is_same = (main_tree == new_main_tree);
if( !is_same )
{
main_tree.debugPrint();
new_main_tree.debugPrint();
}
QVERIFY2( is_same, "AbsBehaviorTree comparison fails" );
is_same = closed_tree == new_closed_tree;
if( !is_same )
{
closed_tree.debugPrint();
new_closed_tree.debugPrint();
}
QVERIFY2( is_same, "AbsBehaviorTree comparison fails" );
sleepAndRefresh( 500 );
}
void EditorTest::modifyCustomModel()
{
QString file_xml = readFile(":/crossdoor_with_subtree.xml");
main_win->on_actionClear_triggered();
main_win->loadFromXML( file_xml );
QAbstractButton *button_lock = main_win->findChild<QAbstractButton*>("buttonLock");
button_lock->setChecked(false);
auto sidepanel_editor = main_win->findChild<SidepanelEditor*>("SidepanelEditor");
auto treeWidget = sidepanel_editor->findChild<QTreeWidget*>("paletteTreeWidget");
NodeModel jump_model = { NodeType::ACTION,
"JumpOutWindow",
{ {"UseParachute", PortModel() } }
};
sidepanel_editor->onReplaceModel("PassThroughWindow", jump_model);
auto pass_window_items = treeWidget->findItems("PassThroughWindow",
Qt::MatchExactly | Qt::MatchRecursive);
QCOMPARE( pass_window_items.empty(), true);
auto jump_window_items = treeWidget->findItems( jump_model.registration_ID,
Qt::MatchExactly | Qt::MatchRecursive);
QCOMPARE( jump_window_items.size(), 1);
auto abs_tree = getAbstractTree();
auto jump_abs_node = abs_tree.findFirstNode( jump_model.registration_ID );
QVERIFY( jump_abs_node != nullptr);
sleepAndRefresh( 500 );
QCOMPARE( jump_abs_node->model, jump_model );
sleepAndRefresh( 500 );
}
void EditorTest::multipleSubtrees()
{
QString file_xml = readFile(":/test_subtrees_issue_8.xml");
main_win->on_actionClear_triggered();
main_win->loadFromXML( file_xml );
auto abs_tree = getAbstractTree("MainTree");
auto sequence_node = abs_tree.findFirstNode("main_sequence");
QVERIFY( sequence_node != nullptr );
QCOMPARE( sequence_node->children_index.size(), size_t(2) );
int index_1 = sequence_node->children_index[0];
int index_2 = sequence_node->children_index[1];
auto first_child = abs_tree.node(index_1);
auto second_child = abs_tree.node(index_2);
QCOMPARE( first_child->instance_name, tr("MoveToPredefinedPoint") );
QCOMPARE( second_child->instance_name, tr("SubtreeOne") );
sleepAndRefresh( 500 );
}
void EditorTest::editText()
{
QString file_xml = readFile("://show_all.xml");
main_win->on_actionClear_triggered();
main_win->loadFromXML( file_xml );
auto abs_tree = getAbstractTree();
std::list<QLineEdit*> line_editable;
for(const auto& node: abs_tree.nodes())
{
auto lines = node.graphic_node->nodeDataModel()->embeddedWidget()->findChildren<QLineEdit*>();
for(const auto& line: lines)
{
if( line->isReadOnly() == false && line->isHidden() == false)
{
line_editable.push_back( line );
}
}
}
auto container = main_win->currentTabInfo();
auto view = container->view();
for(const auto& line: line_editable)
{
QTest::mouseDClick( line, Qt::LeftButton );
line->selectAll();
sleepAndRefresh( 50 );
QTest::keyClick(line, Qt::Key_Delete, Qt::NoModifier );
sleepAndRefresh( 50 );
QCOMPARE( line->text(), QString() );
QTest::mouseClick( line, Qt::LeftButton );
sleepAndRefresh( 50 );
QTest::keyClicks(view->viewport(), "was_here");
QCOMPARE( line->text(), tr("was_here") );
}
sleepAndRefresh( 500 );
}
void EditorTest::loadModelLess()
{
QString file_xml = readFile("://simple_without_model.xml");
main_win->on_actionClear_triggered();
main_win->loadFromXML( file_xml );
auto models = main_win->registeredModels();
QVERIFY( models.find("moverobot") != models.end() );
const auto& moverobot_model = models.at("moverobot");
// QCOMPARE( moverobot_model.params.size(), size_t(1) );
// QCOMPARE( moverobot_model.params.front().label, tr("location") );
// QCOMPARE( moverobot_model.params.front().value, tr("1") );
}
void EditorTest::longNames()
{
QString file_xml = readFile(":/issue_24.xml");
main_win->on_actionClear_triggered();
main_win->loadFromXML( file_xml );
auto abs_tree = getAbstractTree();
QCOMPARE( abs_tree.nodesCount(), size_t(4) );
auto sequence = abs_tree.node(1);
QCOMPARE( sequence->model.registration_ID, QString("Sequence"));
// second child on the right side.
int short_index = sequence->children_index[1];
auto short_node = abs_tree.node(short_index);
QCOMPARE( short_node->model.registration_ID, QString("short") );
}
void EditorTest::clearModels()
{
QString file_xml = readFile(":/crossdoor_with_subtree.xml");
main_win->on_actionClear_triggered();
main_win->loadFromXML( file_xml );
file_xml = readFile(":/show_all.xml");
main_win->on_actionClear_triggered();
main_win->loadFromXML( file_xml );
auto container = main_win->currentTabInfo();
// auto view = container->view();
auto abs_tree = getAbstractTree();
auto node = abs_tree.findFirstNode( "DoSequenceStar" );
QTimer::singleShot(300, [&]()
{
// No message box expected
QWidget* modal_widget = QApplication::activeModalWidget();
if (dynamic_cast<QMessageBox*>(modal_widget))
{
QKeyEvent* event = new QKeyEvent(QEvent::KeyPress, Qt::Key_Enter, Qt::NoModifier);
QCoreApplication::postEvent(modal_widget, event);
QFAIL("no QMessageBox");
}
});
container->createSubtree( *node->graphic_node, "DoorClosed" );
}
void EditorTest::undoWithSubtreeExpanded()
{
QString file_xml = readFile(":/crossdoor_with_subtree.xml");
main_win->on_actionClear_triggered();
main_win->loadFromXML( file_xml );
auto abs_tree = getAbstractTree("MainTree");
auto subtree_node = abs_tree.findFirstNode("DoorClosed")->graphic_node;
auto window_node = abs_tree.findFirstNode("PassThroughWindow")->graphic_node;
auto subtree_model = dynamic_cast<SubtreeNodeModel*>( subtree_node->nodeDataModel() );
QTest::mouseClick( subtree_model->expandButton(), Qt::LeftButton );
sleepAndRefresh( 500 );
auto scene = main_win->getTabByName("MainTree")->scene();
int node_count_A = scene->nodes().size();
scene->removeNode(*window_node);
sleepAndRefresh( 500 );
abs_tree = getAbstractTree("MainTree");
int node_count_B = scene->nodes().size();
QCOMPARE( node_count_A -1 , node_count_B );
main_win->onUndoInvoked();
scene = main_win->getTabByName("MainTree")->scene();
int node_count_C = scene->nodes().size();
QCOMPARE( node_count_A , node_count_C );
sleepAndRefresh( 500 );
}
QTEST_MAIN(EditorTest)
#include "editor_test.moc"
|
279a2f7b32b8ff446cd2f48faa1e6fd48de3aa4d
|
81361fbb260f3a43f2dfd05474c1bb06c5160d9c
|
/Codeforces/Accepted/443A.cpp
|
fc3be53425542bcc9c04acf86ec5e24296c134bf
|
[] |
no_license
|
enamcse/ACM-Programming-Codes
|
9307a22aafb0be6d8f64920e46144f2f813c493a
|
70b57c35ec551eae6322959857b3ac37bcf615fa
|
refs/heads/master
| 2022-10-09T19:35:54.894241
| 2022-09-30T01:26:24
| 2022-09-30T01:26:24
| 33,211,745
| 3
| 2
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,305
|
cpp
|
443A.cpp
|
//#include <bits/stdc++.h>
//#define _ ios_base::sync_with_stdio(0);cin.tie(0);
#include <iostream>
#include <cstdio>
#include <cstring>
#include <cmath>
#include <cstdlib>
#include <queue>
#include <vector>
#include <algorithm>
#include <cctype>
#include <fstream>
#include <map>
#include <list>
#include <set>
#include <string>
#include <stack>
#include <bitset>
#define sz 50005
#define pb(a) push_back(a)
#define pp pop_back()
#define ll long long
#define fread freopen("input.txt","r",stdin)
#define fwrite freopen("output.txt","w",stdout)
#define inf (1e9)
#define chng(a,b) a^=b^=a^=b;
#define clr(abc,z) memset(abc,z,sizeof(abc))
#define PI acos(-1)
#define fr(i,a,b) for(i=a;i<=b;i++)
#define print1(a) cout<<a<<endl
#define print2(a,b) cout<<a<<" "<<b<<endl
#define print3(a,b,c) cout<<a<<" "<<b<<" "<<c<<endl
#define mod 1000000007
using namespace std;
bool let[26];
int main()
{
#ifdef ENAM
// fread;
// fwrite;
#endif // ENAM
int t, n, m, cas=1;
char line[20000];
gets(line);
int i = 1;
while(i)
{
if(line[i]>='a'&&line[i]<='z') let[ line[i] - 'a' ] = true;
else if(line[i]=='}') break;
i++;
}
n = 0;
for (int i = 0; i<26; i++)
if(let[i]) n++;
printf("%d", n);
return 0;
}
|
6351cf3671521fcbe60a68b91e06abc44223b8f0
|
5f5671acf1e7df46767888e040702fe4e438bb8e
|
/c_bootcamp/day02/ex04/Fixed.class.hpp
|
b2af87862fb4f8c1b191ca2894333f1ae8af8f60
|
[] |
no_license
|
charlmoller/wethinkcode_
|
1057c5ca29426cf4be0b0babaf5dc0cfea216abb
|
4e53a0c76e4fdfc0fcc11d3820fed0cf4fb8b888
|
refs/heads/master
| 2022-12-22T12:02:27.256368
| 2021-08-23T13:50:03
| 2021-08-23T13:50:03
| 241,535,644
| 0
| 0
| null | 2022-12-10T18:44:25
| 2020-02-19T04:51:41
|
C
|
UTF-8
|
C++
| false
| false
| 1,717
|
hpp
|
Fixed.class.hpp
|
#ifndef FIXED_CLASS_HPP
#define FIXED_CLASS_HPP
#include <iostream>
#include <ostream>
#include <cmath>
class Fixed {
private:
static const int bits;
int val;
public:
int getRawBits( void ) const;
void setRawBits( int const raw );
float toFloat( void ) const;
int toInt( void ) const;
Fixed();
Fixed( const Fixed& cc );
Fixed( const int val );
Fixed( const float val );
~Fixed();
Fixed& operator=( const Fixed& cc );
Fixed& operator=( int i );
Fixed& operator=( float f );
friend std::ostream& operator<<( std::ostream& out, const Fixed& fix );
bool operator==( const Fixed& rhs );
bool operator!=( const Fixed& rhs );
bool operator>( const Fixed& rhs );
bool operator>=( const Fixed& rhs );
bool operator<( const Fixed& rhs );
bool operator<=( const Fixed& rhs );
// A Caltech professor suggests implementing compound assignment operators ...
Fixed& operator+=( const Fixed &rhs );
Fixed& operator-=( const Fixed &rhs );
Fixed& operator*=( const Fixed &rhs );
Fixed& operator/=( const Fixed &rhs );
// ... and using them to handle arithmetic operators
const Fixed& operator+( const Fixed& rhs );
const Fixed& operator-( const Fixed& rhs );
const Fixed& operator*( const Fixed& rhs );
const Fixed& operator/( const Fixed& rhs );
Fixed& operator++();
Fixed operator++( int );
Fixed& operator--();
Fixed operator--( int );
static Fixed& min( Fixed&, Fixed& );
static Fixed& max( Fixed&, Fixed& );
static const Fixed& min( const Fixed&, const Fixed& );
static const Fixed& max( const Fixed&, const Fixed& );
};
#endif // FIXED_CLASS_HPP
|
895d4190d8d319ab2a5389dbffab45d29216f9a7
|
996d44fce3dd398731edef6479bfd4f88e348fb9
|
/src/stereo_sensors/StereoSensor.h
|
e0019fa92f29222574a98a5752d0a525a12bf153
|
[] |
no_license
|
vislab-tecnico-lisboa/foveated_stereo
|
43c5b9769180004578bfe75947044928c2a8a5a6
|
4b67f44c8d3ae6afa58a3e474059a53f2a646c8f
|
refs/heads/master
| 2020-05-29T20:44:39.067830
| 2018-08-31T12:21:12
| 2018-08-31T12:21:12
| 33,475,520
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,576
|
h
|
StereoSensor.h
|
#ifndef STEREOSENSOR_H
#define STEREOSENSOR_H
#include "UnscentedTransform.h"
#include "StereoData.h"
#include <opencv2/core/core.hpp>
#include <opencv2/imgproc/imgproc.hpp>
class StereoSensor : public UnscentedTransform<cv::Mat>
{
protected:
std::vector<cv::Mat> diff;
virtual void computeSigmaPoints() = 0;
virtual void rectifySigmaPoints(const cv::Mat & H1,
const cv::Mat & H2,
const cv::Mat & stereo_rectification_map1_left,
const cv::Mat & stereo_rectification_map2_left,
const cv::Mat & stereo_rectification_map1_right,
const cv::Mat & stereo_rectification_map2_right) = 0;
virtual void findWarpedCorrespondences(const cv::Mat & disparities_, cv::Mat & correspondences_map_1, cv::Mat & correspondences_map_2) = 0;
private:
void triangulate(const cv::Mat & correspondences_map_1,
const cv::Mat & correspondences_map_2,
const double & translation);
void closestPointsLines(const double & base_line,
const cv::Vec3d & camera_1_point,
const cv::Vec3d & camera_2_point,
cv::Vec3d & resulting_point);
public:
StereoSensor(const int & width_,
const int & height_,
const int & number_of_disparities_,
const int & min_disparity_,
const double & L_,
const double & alpha_,
const double & ki_,
const double & beta_,
const double & scaling_factor_,
const std::string & reference_frame
);
void computeUncertainty(const cv::Mat & disparities_,
const cv::Mat & H1,
const cv::Mat & H2,
const cv::Mat & stereo_rectification_map1_left,
const cv::Mat & stereo_rectification_map2_left,
const cv::Mat & stereo_rectification_map1_right,
const cv::Mat & stereo_rectification_map2_right,
const double & translation);
StereoData stereo_data;
protected:
double center_height; // cartesian x center of the sensor
double center_width; // cartesian y cennter of the center
int number_of_disparities;
int min_disparity;
};
#endif // STEREOSENSOR_H
|
981e109aa22d9151908ca5891123dac7627494c0
|
d93e260d834948d99db86e8c3c97e5f298d8a071
|
/src/Engine/GameFramework/Private/ECS/System.cpp
|
ba000e864f9aedf3d58dcc3b998b1a43103e552c
|
[] |
no_license
|
matthiascy/MoteurDeJeux
|
f8a77428afc29e7fd5d699ae16f44b90a3c83307
|
f610862a5bba08e8b6279d6de3eba1ae1e83597d
|
refs/heads/master
| 2020-09-06T06:06:49.793016
| 2020-01-14T02:36:28
| 2020-01-14T02:36:28
| 220,345,046
| 2
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 163
|
cpp
|
System.cpp
|
#include <GameFramework/Public/ECS/System.hpp>
System::System(const String& name, Engine* engine, Object* parent)
: Object(name, parent), m_engine{engine}
{ }
|
a8060558c0bfbc8753794a4786862ad81e329e51
|
d2aac593538c407c7d54b2efbdf1008b1ccbc6c3
|
/Practice02/2.9.cpp
|
7709588a87bcf0df3dedf76a31beb3685c4c8a4e
|
[] |
no_license
|
kunghua999/CS31
|
afd867cdd14859f75a7571fb4dd95612b8ddc82b
|
cfc50dfd4250a717e55e8963def5f0e5a5821ac1
|
refs/heads/master
| 2021-05-01T23:35:34.020272
| 2016-12-31T17:45:39
| 2016-12-31T17:45:39
| 77,750,556
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 202
|
cpp
|
2.9.cpp
|
#include <iostream>
using namespace std;
int main()
{
int x = 100;
if (x < 6666)
if (x < 5555)
if (x < 4444)
if (x < 2222)
cout << "x < 2222" << endl;
else
cout << "x = 100" << endl;
}
|
16c137efeff905121b6a7d5b0ff642c9ad1e2b4a
|
ed00331bc4bd59ac815559062324022c0a1dac61
|
/src/stdafx.h
|
7f9cdb10cda38b425728f8676b7a3c40fe4376f8
|
[] |
no_license
|
EvGamer/Blaster-Master-Remake
|
c5b000fe5fd207a8a765440ea857badfbf8775c1
|
fb996327023ed7cca94077bdef624e6e2c01eda1
|
refs/heads/master
| 2022-03-13T10:49:36.278054
| 2022-01-25T20:55:38
| 2022-01-25T20:55:38
| 95,442,290
| 2
| 0
| null | 2022-01-25T20:55:39
| 2017-06-26T12:05:39
|
C++
|
UTF-8
|
C++
| false
| false
| 117
|
h
|
stdafx.h
|
#include <math.h>
#include <algorithm>
#define SUPPORT_FILEFORMAT_TGA 1
#include <raylib.h>
#include <string>
|
c88b708bf95cdbca7bb3164b4567586bb930f8b8
|
51a6ade65cf47e4df4b292d801d4e26adcc5fc10
|
/02-3-debug.cpp
|
1ef73aa893821569b87fb2ba7d592fbfc71bc35c
|
[] |
no_license
|
yuhaim/PTA
|
108dfd3c958ed91966497b8186b07f17166e8a06
|
8dffbd6f24a33e5ae8f1c609f850b2c745c4a347
|
refs/heads/master
| 2020-03-29T20:09:08.781914
| 2019-02-26T01:50:07
| 2019-02-26T01:50:07
| 150,298,095
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,966
|
cpp
|
02-3-debug.cpp
|
#include <iostream>
#include <vector>
using namespace std;
struct Node{
int data;
int next;
};
struct Node mem_space[100001];
int reverse_list(int start_addr, int K)
{
int curr_addr, prev_addr;
prev_addr = -1;
curr_addr = start_addr;
int count = 0;
while(count < K){
int temp = mem_space[curr_addr].next;
mem_space[curr_addr].next = prev_addr;
prev_addr = curr_addr;
curr_addr = temp;
count++;
}
return prev_addr;
}
int main()
{
int start_addr, N, K;
cin >> start_addr >> N >> K;
for(int i=0; i<N; i++){
int addr, data, next;
cin >> addr >> data >> next;
struct Node node;
node.data = data;
node.next = next;
mem_space[addr] = node;
}
int len = 0;
int temp = start_addr;
while(temp!=-1){
len++;
temp = mem_space[temp].next;
}
int prev_tail_addr;
int curr_addr, prev_addr;
prev_addr = -1;
curr_addr = start_addr;
for(int i=0; i<len; i+=K){
if(i==K)
start_addr = prev_addr;
if(i>=K)
mem_space[prev_tail_addr].next = curr_addr;
if(i>len-K)
break;
prev_tail_addr = curr_addr;
int count = 0;
while(count < K){
int temp = mem_space[curr_addr].next;
mem_space[curr_addr].next = prev_addr;
prev_addr = curr_addr;
curr_addr = temp;
count++;
}
}
temp = start_addr;
while(temp!=-1){
if(mem_space[temp].next!=-1){
printf("%05d %d %05d\n",
temp,
mem_space[temp].data,
mem_space[temp].next);
}else{
printf("%05d %d %d\n",
temp,
mem_space[temp].data,
mem_space[temp].next);
}
temp = mem_space[temp].next;
}
return 0;
}
|
185dcb90b286fade31a8d9695f3147eeb11c3752
|
ba87cc146b2ea6b705a675460ab3c6a70909e325
|
/Contests/Semana 5/Problema A - Verificação no Vetor 01.cpp
|
73e20ee597ccafa4f051799d849cef9e97fa5b63
|
[] |
no_license
|
RoberttyFreitas/Grupo-OBI-2020
|
3437d820e05aad529a29bda6b611d121c4ec9d66
|
71fee8c05adfd96df2787713a7072c079b5ab983
|
refs/heads/master
| 2022-10-19T17:44:53.339423
| 2020-06-11T17:08:59
| 2020-06-11T17:08:59
| 256,434,549
| 2
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 441
|
cpp
|
Problema A - Verificação no Vetor 01.cpp
|
#include <bits/stdc++.h>
using namespace std;
bool busca(vector<int> v, int x){
for(int i = 0; i < (int) v.size(); i++){
if(v[i] == x){
return true;
}
}
return false;
}
int main(){
int N, Q, aux;
vector<int> v;
cin >> N;
while(N--){
cin >> aux;
v.push_back(aux);
}
cin >> Q;
while(Q--){
cin >> aux;
if(busca(v, aux)){
cout << "Sim" << endl;
}else{
cout << "Nao" << endl;
}
}
return 0;
}
|
40d917911c87dfc5adfe634c4aa22ce4d9880191
|
f4167b3b4f5977748edd41b3d1c267cc25be7c54
|
/Hard/052_N-QueensII.cpp
|
bdf55175c5878c0304b3c6ee963f801d562a0ce4
|
[] |
no_license
|
DeanChensj/LeetCode
|
a5b2315ad10e25ba47bdec211bd5ab3c097a8514
|
fe85957cd2fef592bed052534d251dc9a2d2a0b1
|
refs/heads/master
| 2021-01-10T18:02:50.531671
| 2016-05-13T06:22:20
| 2016-05-13T06:22:20
| 49,619,720
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 874
|
cpp
|
052_N-QueensII.cpp
|
#include <iostream>
#include <vector>
#include <string>
using namespace std;
bool judger(int n, int pt, int *table){
for (int i = 0; i < pt; ++i) {
if (table[i] == table[pt] || (table[i] + pt == table[pt] + i) \
|| (table[i] - pt == table[pt] - i)) {
return false;
}
}
return true;
}
void nQueensHelper(int n, int pt, int *table, int &result){
if (pt == n) {
result++;
return;
}
for (int i = 0; i < n; ++i) {
table[pt] = i;
if (judger(n, pt, table)) {
nQueensHelper(n, pt+1, table, result);
}
}
return;
}
int totalNQueens(int n) {
int *table = new int[n];
int result = 0;
for (int i = 0; i < n; ++i) {
table[0] = i;
nQueensHelper(n, 1, table, result);
}
cout << "n = " << n << "\nresult = " << result << endl;
return result;
}
int main(int argc, char const *argv[])
{
totalNQueens(13);
return 0;
}
|
dcf3ae40ab0a1cff655bb2d6fe0f92b8d151eabf
|
c9a688bdc5007daa871cfe8232679469ebc87586
|
/Collision Detection/Point.cpp
|
590d6217bd802c45853015d6dfdbbbe74a90963c
|
[] |
no_license
|
aeoncleanse/C-Practice
|
5dc97aa0d2ab02685aa4bb4517b843472eda5160
|
f6a557c216b6feb64602e31a56b38bddea39f9bd
|
refs/heads/master
| 2021-04-12T11:47:37.139945
| 2018-10-27T12:45:15
| 2018-10-27T12:47:10
| 126,243,690
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 239
|
cpp
|
Point.cpp
|
// Point struct implementation
#include "Point.h"
// I'm hoping this setup means you can't get a Point without it having x and y set. We don't want that!
template <typename IntDouble>
Point<IntDouble>::Point(IntDouble x, IntDouble y) {}
|
4219a72dcd5c8e03e38f5a45d75f80bb7d43ee44
|
7180fa14129eff079ee0201fa5127bff7d7c3352
|
/n_queen/queen.cpp
|
0392584c63caf8e97018c88a8782c7b72638bdcd
|
[] |
no_license
|
Ckins/c-sicily
|
8943d2840426031bdbd3377a5f4cde6291fec9c6
|
1cc43423d6f2c3ff119dd66f71ad2beac62eac1c
|
refs/heads/master
| 2021-01-22T08:59:33.696231
| 2017-05-15T00:42:02
| 2017-05-15T00:42:02
| 42,938,937
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,697
|
cpp
|
queen.cpp
|
#include <iostream>
#include <vector>
#include <cstdlib>
using namespace std;
bool chessboard[100][100];
class queen {
public:
queen(int r, int c) {
row = r;
col = c;
}
int row;
int col;
};
vector<queen> queenStack;
bool isValid(queen* chess, int n);
void display(int n);
int main() {
int n;
cin >> n;
int total = 0;
int i = 0;
int j = 0;
for (j = 0; j < n; j++) {
for (i = 0; i < n; i++) {
chessboard[j][i] = false;
}
}
queen* chess = new queen(0, 0);
queenStack.insert(queenStack.begin(), *chess);
bool isBacking = false;
while (!queenStack.empty()) {
int cur = queenStack.front().row;
if (cur == n-1 && !isBacking) {
display(n);
total++;
}
if (!isBacking) {
chess = new queen(cur+1, 0);
} else {
chess = new queen(cur, queenStack.front().col);
queenStack.erase(queenStack.begin());
chess->col += 1;
}
while (!isValid(chess, n)) {
if (chess->col < n) {
chess->col += 1;
} else {
break;
}
}
if (chess->col >= n) {
delete chess;
isBacking = true;
} else {
queenStack.insert(queenStack.begin(), *chess);
isBacking = false;
}
}
cout << "There totally exists " << total << " solutions" << endl;
return 0;
}
void display(int n) {
int i = 0;
int j = 0;
for (j = 0; j < n; j++) {
for (i = 0; i < n; i++) {
chessboard[j][i] = false;
}
}
cout << endl << endl << endl;
vector<queen>::iterator it = queenStack.begin();
for (; it != queenStack.end();it++) {
chessboard[it->row][it->col] = true;
}
for (i = 0; i < n; i++) {
for (j = 0; j < n; j++) {
if (chessboard[i][j]) {
cout << "1" << " ";
} else {
cout << "0" << " ";
}
}
cout << endl;
}
}
bool isValid(queen* chess, int n) {
if (chess->col >= n) {
return false;
}
vector<queen>::iterator it = queenStack.begin();
for (;it != queenStack.end(); it++) {
int col = (*it).col;
int row = (*it).row;
if (col == chess->col) {
return false;
}
if (row == chess->row) {
return false;
}
if (col - chess->col == row - chess->row) {
return false;
}
if (col - chess->col == chess->row - row) {
return false;
}
}
return true;
}
|
f33b47bda5c64f7855509f1d1a2794eb0dd27b29
|
7217b6e38f465f3109365038ea955b1ca09f0533
|
/cs174projectCleanup/GrenadeEntity.h
|
bcb2fbe0719aa03a3dda0b08839be6fb836130b6
|
[] |
no_license
|
elixiroflife4u/cs174a_term_project
|
76d1a679c62a322a256433f67728a2045e3c22e9
|
6a1e8dc2e35f10d12eaabbd40a28182d8d8fbdf9
|
refs/heads/master
| 2020-04-06T04:02:14.653151
| 2017-08-04T21:39:37
| 2017-08-04T21:39:37
| 2,672,693
| 2
| 17
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,927
|
h
|
GrenadeEntity.h
|
#ifndef _GRENADEBULLET
#define _GRENADEBULLET
#include "BulletEntity.h"
/** @brief The grenade arcs when shot into the world
* with an initial velocity and creates and explosion
* when it collides with another solid game entity
* If possible, a light is attached to the grenade on creation
*
*/
class GrenadeEntity: public BulletEntity{
private:
PointLight* p;
int _lifeCount;
public:
/** @brief Initializes the grenade with the positio and force */
GrenadeEntity(vec3 pos, vec3 dir, float force=5)
:BulletEntity(pos,20,ID_BULLET_GRENADE),_lifeCount(0)
{
MobileEntity::setVel(normalize(dir)*force);
setModel(DrawableEntity(NULL,"Resources/grenade.obj"));
scale(.75,.75,.75);
getModel().setDiffuseColor(1,0,0);
getModel().scale(.75,.75,.75);
getModel().setShininess(100);
getModel().setHighlightColor(.5,0,0);
this->setHitbox(CollisionBox(vec3(1.5,1.5,1.5)));
p=new PointLight(vec3(1,0,0),1,5);
Globals::addLight(p);
p->setParent(this);
}
/** @brief Deletes the light from the entity when the grenade is destroyed
*/
~GrenadeEntity(){
if(!Globals::deleteLight(p)){
delete p;
}
}
/** @brief Moves the grenade and causes the arch over time
* as well as the blinking of the attached light
*/
void update(){
increaseVel(Globals::grav);
translate(getVel());
rotate(15,0,15);
vec3 dir=Globals::getPlayer()->getTranslate()-getTranslate();
if(dot(dir,dir)>pow(300.0,2)){
setDelete();
}
_lifeCount++;
if(_lifeCount%6<3){
getModel().setHighlightColor(.25,0,0);
p->setBrightness(1);
}
else{
getModel().setHighlightColor(.75,0,0);
p->setBrightness(5);
}
}
/** @brief when the grenade collides with something, it creates an explosion
*/
void onCollide(const GameEntity& g){
Explosion* e=new Explosion(5);;
e->setTranslate(getTranslate());
Globals::addSoftEntity(e);
setDelete();
}
};
#endif //_GRENADEBULLET
|
ea0bb62ee9c9116906810e4e13d06e1e9e69fbfa
|
31e144bfe008ce67db00d01777012c3a8153990e
|
/537/537.cpp
|
3e0944e253c2bab45deb8f96dd173f6061eaa107
|
[] |
no_license
|
reliveinfire/codes
|
0d285dd002bfef5732182144be19681dd22091e2
|
69750ebf708bcbf8ac7723c19f5370793cf8f95b
|
refs/heads/master
| 2021-01-15T18:27:23.743076
| 2018-05-07T09:33:51
| 2018-05-07T09:33:51
| 99,788,745
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,632
|
cpp
|
537.cpp
|
#include <iostream>
#include <string>
#include <map>
#include <vector>
#include <limits.h>
#include <queue>
#include <stack>
#include <sstream>
#include <algorithm>
using namespace std;
class compNum{
public:
int rr;
int ii;
compNum(int r,int i){rr = r;ii = i;}
compNum(){}
};
class Solution {
public:
string complexNumberMultiply(string a, string b){
int ar, ai, br, bi, ansR, ansI;
string result;
stringstream ss;
compNum cc;
cc = parse(a);
ar = cc.rr;ai = cc.ii;
cc = parse(b);
br = cc.rr;bi = cc.ii;
ansR = (ar * br) - (ai*bi);
ansI = (ar * bi) + (ai * br);
cout << ar <<":"<< ai<<endl;
cout << br <<":"<< bi<<endl;
ss << ansR;ss << "+";ss << ansI;ss << "i";
result += ss.str();
return result;
}
compNum parse(string s)
{
compNum cc;
int negative = 0;
string tmp;
for (int i = 0 ; i < s.size() ; i++){
if (s[i] == '-')
negative = 1;
else if (s[i] == '+'){
cc.rr = atoi(tmp.c_str());
if (negative)
cc.rr = 0- cc.rr;
negative = 0;
tmp.clear();
} else if(s[i] == 'i'){
cc.ii = atoi(tmp.c_str());
if (negative)
cc.ii = 0- cc.ii;
}else
tmp += s.substr(i,1);
}
return cc;
}
};
#define genVector(data, array) vector<int> data(array, array+sizeof(array)/sizeof(array[0]));
int main()
{
vector<int> ret_vec;
int A[] = {1,2,3};
int B[] = {1,2,3};
string sa("78+-76i");
string sb("-86+72i");
genVector(da, A);
genVector(db, B);
Solution sol;
string ret;
ret = sol.complexNumberMultiply(sa,sb);
cout << ret << "\n";
for (int i = 0 ; i < ret_vec.size() ; i++)
cout << ret_vec[i] << " ";
cout <<endl;
return 0;
}
|
ad06e9e72a19e57eba58c64cbdae85962c60226f
|
0405175b6d79bde7dcdf276f4a1036c587e41a9a
|
/src/image/DepthImage.cpp
|
012fb2e78e5389004744b4834451bed4bcb4f119
|
[] |
no_license
|
stasgora/vulkan-test
|
307c9837be9357d1e738a31d5918e1ddcdfd6735
|
3743d7a40e1b6f8c623e38308b2a680f5ec5b59d
|
refs/heads/master
| 2021-08-04T19:12:00.038477
| 2020-10-21T18:03:53
| 2020-10-21T18:03:53
| 227,712,856
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,690
|
cpp
|
DepthImage.cpp
|
#include "DepthImage.h"
#include "ImageUtils.h"
void vkr::DepthImage::createDepthResources(const vk::Extent2D &extent) {
auto depthFormat = findDepthFormat(deviceManager);
ImageUtils::createImage(deviceManager, extent.width, extent.height, depthFormat, vk::ImageTiling::eOptimal,
vk::ImageUsageFlagBits::eDepthStencilAttachment, vk::MemoryPropertyFlagBits::eDeviceLocal, image, imageMemory);
imageView = ImageUtils::createImageView(device, image, depthFormat, vk::ImageAspectFlagBits::eDepth);
}
vk::Format vkr::DepthImage::findSupportedFormat(const DeviceManager &deviceManager, const std::vector<vk::Format> &candidates, vk::ImageTiling tiling, const vk::FormatFeatureFlags& features) {
for (const auto &format : candidates) {
auto props = deviceManager.physicalDevice.getFormatProperties(format);
if (tiling == vk::ImageTiling::eLinear && (props.linearTilingFeatures & features) == features)
return format;
else if (tiling == vk::ImageTiling::eOptimal && (props.optimalTilingFeatures & features) == features)
return format;
}
throw std::runtime_error("failed to find supported format");
}
vkr::DepthImage::DepthImage(const vkr::DeviceManager &deviceManager) : BaseImage(deviceManager) {}
vk::Format vkr::DepthImage::findDepthFormat(const DeviceManager &deviceManager) {
return findSupportedFormat(deviceManager, {vk::Format::eD32Sfloat, vk::Format::eD32SfloatS8Uint, vk::Format::eD24UnormS8Uint},
vk::ImageTiling::eOptimal, vk::FormatFeatureFlagBits::eDepthStencilAttachment);
}
bool vkr::DepthImage::hasStencilComponent(vk::Format format) {
return format == vk::Format::eD32SfloatS8Uint || format == vk::Format::eD32SfloatS8Uint;
}
|
e8acccea59d989663f158a29544ab17f103aade3
|
c4edaf97a432d8c6a58465098ec3fab301e4e9c1
|
/finalProject3/src/Cow.h
|
49d3e6dd8f4325a84cc42af0e1677c2526531fef
|
[] |
no_license
|
elenaleegold/golde584_dtOF_2018
|
9fe333f40704c7ecc4c4cc54b3185838cf275246
|
5fd312dd390f78ef2492851c5af77b29e773150b
|
refs/heads/master
| 2020-03-27T14:26:28.690870
| 2018-12-11T23:40:18
| 2018-12-11T23:40:18
| 146,662,618
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 643
|
h
|
Cow.h
|
#pragma once
#include "ofMain.h"
class Cow : public ofBaseApp {
public:
Cow();
Cow(glm::vec2 _pos, glm::vec2 _vel, glm::vec2 _acc, float _radius);
Cow(glm::vec2 _pos, glm::vec2 vel, glm::vec2 acc);
Cow(glm::vec2 _pos, glm::vec2 vel, glm::vec2 acc, float radius, string s);
glm::vec2 pos, vel, acc;
float radius;
void update();
void draw();
int dirX, dirY;
float lerp;
bool isCaught;
void setPos(glm::vec2 p);
ofImage cow;
int deg;
int rad;
void setVelocity(glm::vec2 velocity);
void addForce(glm::vec2 force);
void setImage(string s);
ofImage gif[4];
string dir;
bool isEaten();
void setEaten(bool status);
};
|
2ec91f7d03e8709f25eb5df72ce297d964fa1a7f
|
d593ed41ea7210aece5bf1028ad3561407b2a86e
|
/SteelEngine/src/Resource.cpp
|
584bc8ea71f897f837cd712c4e18709996795c5b
|
[] |
no_license
|
shektek/Lords
|
e56969b1811dc4e998347a61d13b0426468407a1
|
de43fecc692714fa7d0749a02b862ac59c07a640
|
refs/heads/master
| 2020-04-16T09:59:21.991760
| 2019-07-15T17:30:06
| 2019-07-15T17:30:06
| 165,484,884
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,229
|
cpp
|
Resource.cpp
|
#include "Resource.h"
Resource::Resource()
{
m_name = "Unknown resource";
m_location = Vector2d(0, 0);
m_maxOutputTons = 0;
m_efficiency = 0;
m_operational = false;
m_resourceType = R_NONE;
m_seasonalOutput = 0;
m_stockpileLoad = 0;
m_stockpileMax = 0;
}
Resource::Resource(ResourceType type, const std::string &name, const Vector2d &location, const double &maxOutput, const double &maxStockpile, bool operational, double startingEfficiency, double startingStock)
{
m_name = name;
m_resourceType = type;
m_location = location;
m_maxOutputTons = maxOutput;
m_stockpileMax = maxStockpile;
m_operational = operational;
m_efficiency = startingEfficiency;
m_stockpileLoad = startingStock;
m_seasonalOutput = m_maxOutputTons * (m_efficiency / 100.0);
}
Resource::Resource(const Resource &other)
{
m_name = other.m_name;
m_efficiency = other.m_efficiency;
m_location = other.m_location;
m_maxOutputTons = other.m_maxOutputTons;
m_operational = other.m_operational;
m_resourceType = other.m_resourceType;
m_seasonalOutput = other.m_seasonalOutput;
m_stockpileLoad = other.m_stockpileLoad;
m_stockpileMax = other.m_stockpileMax;
}
Resource::Resource(Resource *other)
{
m_name = other->m_name;
m_efficiency = other->m_efficiency;
m_location = other->m_location;
m_maxOutputTons = other->m_maxOutputTons;
m_operational = other->m_operational;
m_resourceType = other->m_resourceType;
m_seasonalOutput = other->m_seasonalOutput;
m_stockpileLoad = other->m_stockpileLoad;
m_stockpileMax = other->m_stockpileMax;
}
Resource::~Resource()
{
m_name.clear();
m_location = Vector2d(0, 0);
m_maxOutputTons = 0;
m_efficiency = 0;
m_operational = false;
m_resourceType = R_NONE;
m_seasonalOutput = 0;
m_stockpileLoad = 0;
m_stockpileMax = 0;
}
double Resource::AdjustEfficiency(double addedEfficiency)
{
m_efficiency += addedEfficiency;
m_seasonalOutput = m_maxOutputTons * (m_efficiency / 100.0);
return m_efficiency;
}
double Resource::AdjustStockpileLoad(double addedLoad)
{
double ret = m_stockpileLoad + addedLoad;
m_stockpileLoad += addedLoad;
if (m_stockpileLoad < 0) m_stockpileLoad = 0;
else if (m_stockpileLoad > m_stockpileMax) m_stockpileLoad = m_stockpileMax;
return ret;
}
|
23b7fb49c676e1dd840a9907a39ee83e9d4ce8a7
|
6a8124ccd759c17840835009406e10d3211ded9b
|
/hw04.cpp
|
801c9a4b946ad4ffc75757e61116c781378b359a
|
[] |
no_license
|
drenchedcoat/oop
|
62d94bde83471ff53d8e1d1b3c223942e743e574
|
924fb98442930406a753febcd32fc5246136c159
|
refs/heads/master
| 2021-10-23T21:03:29.254543
| 2019-03-20T01:31:19
| 2019-03-20T01:31:19
| 105,950,583
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 5,332
|
cpp
|
hw04.cpp
|
#include <iostream>
#include <vector>
#include <fstream>
#include <string>
using namespace std;
//--------------WARRIOR CLASS----------------
class Warrior{
private:
string name;
int hp;
bool stat = false; // true= is hired, false= is fired/nobleless
public:
//constructor
Warrior (const string& hisName, const int& hisHP) : name(hisName), hp(hisHP) {}
//setters
void setHP(const int& newHP) { hp = newHP; }
bool status() const { return stat; }
void makeStat(const bool& boole) { stat = boole; }
//getters
string getName() const { return name; }
int getHP() const { return hp; }
};
//--------------NOBLE CLASS----------------
class Noble{
private:
string name;
vector<Warrior*> warriors;
double strength = 0;
public:
//constructor
Noble(const string& nobleName) : name(nobleName){}
//getters
int getStr()const { return strength; }
string getName() const { return name; }
//for ever warrior, decrease its hp by percentage passed in
//if passed in is 0, they die, if 1, no change, if .5, hp halved, etc
void decreaseBy(const double& percent){
for (Warrior* warrior : warriors){
warrior->setHP(warrior->getHP()*percent); //set hp of each warrior
if (percent == 0){ warrior->makeStat(false); } //death case
}strength = strength*percent; //set noble hp
}
bool hire(Warrior &newGuy){
if (newGuy.status()==false){
warriors.push_back(&newGuy); // adds warrior to noble class' vector
strength += newGuy.getHP(); //noble is strengthened
newGuy.makeStat(true); //set noble to busy af
return true;
}
//if warrior already has a noble
cout << "Could not hire, already in a noble." << endl;
return false;
}
void display() const {
cout << name << " has an army of " << warriors.size() << endl;
for (Warrior* warrior : warriors){
cout << "\t" << warrior->getName() << ": " << warrior->getHP() << endl;
}
}
bool fire(Warrior &thisGuy){ //returns false if warrior not in noble
for (size_t i = 0; i < warriors.size(); ++i){
if (warriors[i] == &thisGuy) {
cout << warriors[i]->getName() << ", you're fired! -- " << name << endl;
strength -= warriors[i]->getHP(); //decrease noble HP when fired
warriors[i]->makeStat(false); //warrior is now available for new noble
warriors.erase(warriors.begin() + i); //remove from noble's vector
return true;
}
}
cout << "Could not fire, warrior not in this noble!" << endl;
return false; //if the warrior doesn't exist in noble, return false
}
void battle(Noble &enemyNoble){
cout << name << " battles " << enemyNoble.getName() << endl;
//if any are dead
if (strength==0 && enemyNoble.getStr()==0) { //if both dead
cout << "OH, NO! They're both dead! Yuck!" << endl;
} else if (strength == 0) { //if self is dead
cout << "He's dead, " << enemyNoble.getName() << endl;
} else if (enemyNoble.getStr()==0){ //if enemy is dead
cout << "He's dead, " << name << endl;
}
//if both alive
else{
if (strength > enemyNoble.getStr()){ //if self stronger than enemy
this->decreaseBy(1-(enemyNoble.getStr() / strength)); //decrease self noble hp
enemyNoble.decreaseBy(0); //kill all of enemyNoble
cout << name << " defeats " << enemyNoble.getName() << endl;
} else if (strength < enemyNoble.getStr()){ // if enemy stronger
enemyNoble.decreaseBy(1-(strength / enemyNoble.getStr())); //decrease enemyNoble hp
this->decreaseBy(0); //kill all of self
cout << enemyNoble.getName() << " defeats " << name << endl;
} else { // kill both party woohoo
decreaseBy(0);
enemyNoble.decreaseBy(0);
cout << "Mutual Annihalation: " << name << " and "
<< enemyNoble.getName() << " die at each other's hands" << endl;
}
}
}
};
//-------------------MAIN----------------------
int main() {
Noble art("King Arthur");
Noble lance("Lancelot du Lac");
Noble jim("Jim");
Noble linus("Linus Torvalds");
Noble billie("Bill Gates");
Warrior cheetah("Tarzan", 10);
Warrior wizard("Merlin", 15);
Warrior theGovernator("Conan", 12);
Warrior nimoy("Spock", 15);
Warrior lawless("Xena", 20);
Warrior mrGreen("Hulk", 8);
Warrior dylan("Hercules", 3);
jim.hire(nimoy);
lance.hire(theGovernator);
art.hire(wizard);
lance.hire(dylan);
linus.hire(lawless);
billie.hire(mrGreen);
art.hire(cheetah);
jim.display();
lance.display();
art.display();
linus.display();
billie.display();
art.fire(cheetah);
art.display();
art.battle(lance);
jim.battle(lance);
linus.battle(billie);
billie.battle(lance);
}
|
f60b0d5f7d9fdbff9afd448065aaafd761327c3a
|
b521373d832b678486c81fe37cc056c67022ff54
|
/ch15/accessible1.cc
|
a1dc472cc2a5252e153446f46a6d301ba70f906c
|
[] |
no_license
|
Itsposs/cppprimer
|
097ea428efeceefc2d2865b5b1880b5837e750fa
|
a056dd77e448268909b87bf47cb0c00452255fac
|
refs/heads/master
| 2020-04-29T14:33:17.645754
| 2020-03-15T06:48:34
| 2020-03-15T06:48:34
| 176,199,869
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 507
|
cc
|
accessible1.cc
|
#include <iostream>
class Base {
public:
private:
protected:
int port_mem;
};
class Sneaky : public Base {
friend void clobber(Sneaky&);
friend void clobber(Base&);
public:
// test
void print() { port_mem = 6; std::cout << port_mem << std::endl;}
private:
int j;
};
void clobber(Sneaky &s) {
s.j = s.port_mem = 0;
}
//void clobber(Base &b)
//{
// b.port_mem = 0;
//}
void test() {
Sneaky s1;
clobber(s1);
s1.print();
}
int main(int argc, char *argv[]) {
test();
return 0;
}
|
b9c196e171a6f587bff9825564592d1d6e00977b
|
87b61b564f285858fcda8b50b892c2183bd23d51
|
/client/locale/text_utils.h
|
49eb95036f40485f0f4acd7dd17371db6f320900
|
[
"Apache-2.0"
] |
permissive
|
randyli/google-input-tools
|
e1da92fed47c23cf7b8e2ff63aee90c89e1f0347
|
daa9806724dc6dc3915dbd9d6e3daad4e579bf72
|
refs/heads/master
| 2021-05-18T13:00:21.892514
| 2020-04-11T13:26:33
| 2020-04-11T13:26:33
| 251,252,155
| 0
| 0
|
Apache-2.0
| 2020-03-30T08:58:26
| 2020-03-30T08:58:26
| null |
UTF-8
|
C++
| false
| false
| 3,665
|
h
|
text_utils.h
|
/*
Copyright 2014 Google 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.
*/
//
// This class defines text manipulators and other text utilities which behalf
// differently according to the locale.
#ifndef GOOPY_LOCALE_TEXT_UTILS_H__
#define GOOPY_LOCALE_TEXT_UTILS_H__
#include <locale>
#include <string>
#include "base/basictypes.h"
namespace ime_goopy {
// Interface for manipulating plain text. The operations within this class may
// be varied for different locale. To add a new type of text manipulator,
// please also update the creation of manipulators in LocaleUtil class.
class TextManipulator {
public:
virtual ~TextManipulator() {}
// Expands the selection to the beginning or end of the given word/sentence
// boundary. The starting pos is given as the entry point. The return value
// indicates the number of wchar_t to shift to reach the boundary.
virtual int ExpandToWordBegin(const wstring& text, int pos) = 0;
virtual int ExpandToWordEnd(const wstring& text, int pos) = 0;
virtual int ExpandToSentenceBegin(const wstring& text, int pos) = 0;
virtual int ExpandToSentenceEnd(const wstring& text, int pos) = 0;
// Returns true if the text is starting a new sentence.
virtual bool IsSentenceBegin(const wstring& text) = 0;
// Converts the text into a proper sentence beginning style.
// In English, it is to capitalize the first character of the given string.
virtual void SetSentenceBegin(wstring* text) = 0;
// Check ch if it is valid character based on current language in a word.
virtual bool IsValidCharInWord(wchar_t ch) = 0;
// Check ch if it is valid character based on current language in a sentence.
virtual bool IsValidCharInSentence(wchar_t ch) = 0;
};
// An implementation for Simplified Chinese.
class TextManipulatorZhCn : public TextManipulator {
public:
TextManipulatorZhCn() {}
virtual ~TextManipulatorZhCn() {}
virtual int ExpandToWordBegin(const wstring& text, int pos);
virtual int ExpandToWordEnd(const wstring& text, int pos);
virtual int ExpandToSentenceBegin(const wstring& text, int pos);
virtual int ExpandToSentenceEnd(const wstring& text, int pos);
virtual bool IsSentenceBegin(const wstring& text);
virtual void SetSentenceBegin(wstring* text);
virtual bool IsValidCharInWord(wchar_t ch);
virtual bool IsValidCharInSentence(wchar_t ch);
private:
std::locale locale_;
DISALLOW_COPY_AND_ASSIGN(TextManipulatorZhCn);
};
// An implementation for English.
class TextManipulatorEn : public TextManipulator {
public:
TextManipulatorEn() {}
virtual ~TextManipulatorEn() {}
virtual int ExpandToWordBegin(const wstring& text, int pos);
virtual int ExpandToWordEnd(const wstring& text, int pos);
virtual int ExpandToSentenceBegin(const wstring& text, int pos);
virtual int ExpandToSentenceEnd(const wstring& text, int pos);
virtual bool IsSentenceBegin(const wstring& text);
virtual void SetSentenceBegin(wstring* text);
virtual bool IsValidCharInWord(wchar_t ch);
virtual bool IsValidCharInSentence(wchar_t ch);
private:
DISALLOW_COPY_AND_ASSIGN(TextManipulatorEn);
};
} // namespace ime_goopy
#endif // GOOPY_LOCALE_TEXT_UTILS_H__
|
35bb4f1a96bbb25b02e4be93a358b88e728a7ba0
|
8303918c54dcb35dbece6ed3f8e14c644646230f
|
/xyzfiles/gen_kgrid.cpp
|
d83b36ef833887ff7fbace75a43c14dd9c16effc
|
[] |
no_license
|
GroupProgrammingProject/GPP
|
2c1ad882ded7de55f9a643b334138ca1c973dcc6
|
6183a054b989925545847bf27019a76a1500e64f
|
refs/heads/master
| 2016-09-10T19:45:17.274598
| 2015-03-27T20:55:39
| 2015-03-27T20:55:39
| 29,697,760
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,408
|
cpp
|
gen_kgrid.cpp
|
#include <iostream>
#include <vector>
#include <cmath>
#include <stdlib.h>
#include "../include/readinxyz.h"
#include "../include/kpointsfunctions.h"
// Main for generating an orthorhombic grid of kpoints
// Takes "input.xyz output.kpts A B C" where input.xyz is a structure file, output.kpts is a file to hold a set of points in kspace to be read by the calculation main and A, B and C are the number of kpoints to be generated along the reciprocal a, b and c directions
int main(int argc, char* argv[]) {
if (argc<5){std::cout<<"You should append two files and 3 kpoint grids to the main object!"<<std::endl;}
if (argc!=7){std::cout<<"You should append one xyz, one .kpts file and a kpoint grid to the main!!"<<std::endl;}
std::vector<double> posx, posy, posz,vxin,vyin,vzin; // Required for ReadInXYZ
std::vector<double> lats(3); // Vector to take lattice parameters
std::vector<bool> velspec;
bool pbc = 1; // If generating a kpoint grid then using PBCs
ReadInXYZ (argv[1], &posx, &posy, &posz, &vxin,&vyin,&vzin,&lats, pbc,&velspec); // Read in lattice parameters from .xyz file
int kn[3] = {atoi(argv[3]),atoi(argv[4]),atoi(argv[5])}; // kpoint grid read in from command line
genkgrid(argv[2],&lats,kn,atof(argv[6])); // Generate grid in specified kpoint file
}
|
4306235e4e1da9c0851b6607e6ec938730c8596f
|
39dd6f17e57ce695c6313ec3e9b4717e4cdb3273
|
/Server/Source/ServerService.cpp
|
d6f7c99af2a5973bac7a3a993656fddd559478a2
|
[] |
no_license
|
qqsskk/HPSocketDemo
|
9474cf177ad6f1781a26762dfdc585f4f8cc8f0d
|
9d2b5520e078c7b9464747642a78043150223ccc
|
refs/heads/main
| 2023-07-11T18:08:31.740182
| 2021-08-05T14:33:55
| 2021-08-05T14:33:55
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,369
|
cpp
|
ServerService.cpp
|
//
// Created by lixiaoqing on 2021/7/17.
//
#include <memory>
#include <mutex>
#include "ServerService.h"
#include "ServerListener.h"
#include "Log.h"
#define TAG "ServerService"
static IServerService *serverSingleton = nullptr;
static std::mutex singletonMutex;
IServerService *IServerService::getSingleton() {
if (serverSingleton == nullptr) {
std::unique_lock<std::mutex> lock(singletonMutex);
if (serverSingleton == nullptr) {
serverSingleton = new ServerService();
}
}
return serverSingleton;
}
void IServerService::releaseSingleton() {
if (serverSingleton) {
std::unique_lock<std::mutex> lock(singletonMutex);
if (serverSingleton) {
delete serverSingleton;
serverSingleton = nullptr;
}
}
}
void ServerService::listen(int port) {
auto listener = std::make_shared<ServerListener>();
auto serverPtr = std::make_shared<CTcpPackServerPtr>(listener.get());
auto server = serverPtr->Get();
server->SetMaxPackSize(0x1FFFFF);
server->SetPackHeaderFlag(0x169);
server->SetKeepAliveTime(60 * 1000L);
server->SetSocketBufferSize(1024 * 1024);
auto ret = server->Start("127.0.0.1", port);
if (ret == TRUE) {
Log::info(TAG, "启动 Server 成功!");
} else {
Log::info(TAG, "启动 Server 失败!");
}
}
|
4f310055fa361a099b8489f7080a2325fa557f8a
|
dd2f2a927dc62569773042aed78104a500c8e7fb
|
/easy/climbing_stairs.cpp
|
5ffd38a3dbd39c41540025c12c76738ad68b4fea
|
[] |
no_license
|
zhuangqh/Leetcode
|
7548732c31522ec5736e37ebdbdf26bfd1e9f25b
|
7e78620980f850b3d24bbe4c61294425d783471c
|
refs/heads/master
| 2020-12-24T08:56:39.345621
| 2016-08-30T16:28:25
| 2016-08-30T16:28:25
| 34,942,578
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 363
|
cpp
|
climbing_stairs.cpp
|
#include <iostream>
#include <vector>
class Solution {
public:
int climbStairs(int n) {
std::vector<int> store(n + 1);
store[1] = 1;
store[2] = 2;
for (int i = 3; i <= n; ++i) {
store[i] = store[i - 1] + store[i - 2];
}
return store[n];
}
};
int main() {
Solution a;
std::cout << a.climbStairs(5) << std::endl;
return 0;
}
|
c17b9e039765faca9fe9fe0007f24a09415cfdda
|
c1071a4ab992a322cb3c9d933ab27274da23a317
|
/Classes/GameScene/GameCtrlLayer.h
|
acac32de88ac4de8c95569903f6fc31ddd132d79
|
[] |
no_license
|
thibetabc/TetrisAI
|
07db3a8b6c3b64f80c3d093526feaef960deef4a
|
6b19d2a671f8993abd1c77e8f9c5fb1b8aecd95f
|
refs/heads/master
| 2020-04-03T15:07:50.462463
| 2016-06-11T16:20:47
| 2016-06-11T16:20:47
| 60,915,637
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,293
|
h
|
GameCtrlLayer.h
|
//
// GameCtrlLayer.h
// AITetris
//
// Created by yangjh on 15/4/28.
//
//
#ifndef __AITetris__GameCtrlLayer__
#define __AITetris__GameCtrlLayer__
#include <stdio.h>
USING_NS_CC;
class GameCtrlLayerDelegate
{
public:
virtual void gameCtrlLayerClickStartGame() = 0;
virtual void gameCtrlLayerStartAI(bool AIOn) = 0;
virtual void gameCtrlLayerClickAccelerate() = 0;
virtual void gameCtrlLayerClickDecelerate() = 0;
virtual float gameCtrlLayerGetAISpeed() = 0;
virtual void gameCtrlLayerClickLeft() = 0;
virtual void gameCtrlLayerClickRight() = 0;
virtual void gameCtrlLayerClickRotate() = 0;
virtual void gameCtrlLayerClickThrowDown() = 0;
};
class GameCtrlLayer : public Layer
{
public:
virtual bool init();
CREATE_FUNC(GameCtrlLayer);
void setDelegate(GameCtrlLayerDelegate *delegate) { m_delegate = delegate; }
private:
void clickStartGameButton();
void clickAISwitchButton();
void clickLeftButton();
void clickRightButton();
void clickUpButton();
void clickDownButton();
private:
GameCtrlLayerDelegate *m_delegate;
bool m_AIOn;
Label *m_labelAISwitch;
Label *m_labelAISpeed;
Menu *m_menuLeft;
Menu *m_menuRight;
};
#endif /* defined(__AITetris__GameCtrlLayer__) */
|
8d19df9c025e8740d1575de8918f294cc06a7a67
|
c83f1f84d00b9fa2640a362e59c4322d6e268116
|
/use a cabeça/Composed_Patterns/Composed_Patterns/src/abstract/Quackable.h
|
25594f478ecfb5670dea33810e6488a15be55177
|
[
"MIT"
] |
permissive
|
alissonads/Design-Patterns-cplusplus
|
9a2936fa7d3cd95c6816e44511eac132e10e96be
|
0e56fbc0c1877b9edf2ad5efafbb9a01fa94d748
|
refs/heads/master
| 2020-06-28T01:06:45.933658
| 2019-08-01T18:39:55
| 2019-08-01T18:39:55
| 200,101,824
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 286
|
h
|
Quackable.h
|
#pragma once
#include "QuackObservable.h"
class Quackable : public QuackObservable
{
public:
virtual ~Quackable() {}
virtual void quack() = 0;
virtual void registerObserver(Observer *observer) = 0;
virtual void notifyObservers() = 0;
virtual std::string getName() const = 0;
};
|
c6d9b627cf4d3cca8e995570ed88e4ba2f18fe01
|
c14e12e003166834d3e5b38825fa4a2c6dd118f5
|
/LGBITFLD.CPP
|
92b49e776033afebb107616178eca32fd2730c4d
|
[] |
no_license
|
hindochan/Internet-Payment-Gateway
|
ec36733675d66f28a6153f83cd20d37031d3da9a
|
3a187606a8763620f1bfc04fb5d6153a9b11fe7c
|
refs/heads/main
| 2023-08-21T12:03:16.693186
| 2021-10-11T23:04:35
| 2021-10-11T23:04:35
| 416,111,208
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 3,759
|
cpp
|
LGBITFLD.CPP
|
/***********************************************************************
* LAG - Source file header
*
* Layer:
* Module:
* $Logfile: $
* Originator: Adam Hawley
* $Revision: $
* on $Date: $
* by $Author: $
*
* Synopsis:
*
* Notes: None.
*
************************************************************************
*
* (C) Copyright 1996, Logica UK Ltd. All rights reserved.
*
************************************************************************
*/
#include <math.h>
#include "LGbitfld.h"
/****************************************************************************
*
* MEMBER FUNCTION DEFINITION
*
* Name: BitMapField::BitMapField
*
* Synopsis: Constructor for class object
*
* Input parameters: None
*
* Output parameters: None
*
* Return value:
*
* Description:
*
* Notes:
*
****************************************************************************
*/
BitMapField::BitMapField(WORD nDataLength)
: Field(nDataLength)
{
// Initialise variables
}
/****************************************************************************
*
* MEMBER FUNCTION DEFINITION
*
* Name: BitMapField::~BitMapField
*
* Synopsis: Destructor for class object
*
* Input parameters: None
*
* Output parameters: None
*
* Return value:
*
* Description:
*
* Notes:
*
****************************************************************************
*/
BitMapField::~BitMapField()
{
}
/****************************************************************************
*
* MEMBER FUNCTION DEFINITION
*
* Name: BitMapField::SetBit
*
* Synopsis: Sets specified bit in string
*
* Input parameters: Bit number to set - starts at 1
*
* Output parameters: None
*
* Return value: None
*
* Description:
*
* Notes:
*
****************************************************************************
*/
void BitMapField::SetBit(WORD nIndex)
{
if (0 < nIndex && nIndex <= (m_nDataLength * 8))
{
char *pcTemp;
pcTemp = &m_pcData[(nIndex - 1)/m_nDataLength];
*pcTemp = *pcTemp | (char)pow(2,(7 - (nIndex -1)%8));
}
}
/****************************************************************************
*
* MEMBER FUNCTION DEFINITION
*
* Name: BitMapField::ClearBit
*
* Synopsis: Clears specified bit in string
*
* Input parameters: Bit number to clear - starts at 1
*
* Output parameters: None
*
* Return value: None
*
* Description:
*
* Notes:
*
****************************************************************************
*/
void BitMapField::ClearBit(WORD nIndex)
{
if (0 < nIndex && nIndex <= (m_nDataLength * 8))
{
char *pcTemp;
pcTemp = &m_pcData[(nIndex - 1)/m_nDataLength];
*pcTemp = *pcTemp & (255 - (char)pow(2,(7 - (nIndex -1)%8)));
}
}
/****************************************************************************
*
* MEMBER FUNCTION DEFINITION
*
* Name: BitMapField::IsBitSet
*
* Synopsis: Tests a particular bit
*
* Input parameters: Bit number to test - starts at 1
*
* Output parameters: None
*
* Return value: BOOL
*
* Description:
*
* Notes:
*
****************************************************************************
*/
BOOL BitMapField::IsBitSet(WORD nIndex)
{
BOOL bBool = FALSE;
if (0 < nIndex && nIndex <= (m_nDataLength * 8))
{
if ((m_pcData[(nIndex - 1)/m_nDataLength] << ((nIndex - 1)%8)) & 128)
bBool = TRUE;
}
return bBool;
}
|
236bfdfd219c1fe703080205b9b01bcdd6968597
|
45e8cfc4cc57f2011dabe588c2db61a7d55b4eb5
|
/bai1_pg1.cpp
|
f6456dff493dc61f65bd7bcb8101079265d80087
|
[] |
no_license
|
0xj4m35/C-Fundamental
|
27b7a2e4af5c6c36a55d470ce407aeab1c012d02
|
74233fc8221507f6423a2ce7f9c52828576834e4
|
refs/heads/master
| 2023-05-11T20:32:48.979471
| 2018-07-11T17:27:42
| 2018-07-11T17:27:42
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 332
|
cpp
|
bai1_pg1.cpp
|
#include <stdio.h>
#include <math.h>
int main(){
float a,b,c;
float p, s;
printf("Enter a,b,c : ");
scanf("%f%f%f", &a, &b, &c);
if (a+b > c && a+c > b && b+c > a) {
p = (a+b+c)/2;
s=sqrt(p*(p-a)*(p-b)*(p-c));
printf("This is a triangle with square = %.2f", s);
} else
printf("This isn't a triangle.");
return 0;
}
|
7c4ecd06c3aaa2eca2191b5356d9aef2d33d81fc
|
a6bb89b2ff6c1fc8c45a4f105ef528416100a360
|
/examples/tut6/mipmap/texture.h
|
8685156f4658d5996640a1e979d09e0f2efb7dce
|
[] |
no_license
|
dudochkin-victor/ngxe
|
2c03717c45431b5a88a7ca4f3a70a2f23695cd63
|
34687494bcbb4a9ce8cf0a7327a7296bfa95e68a
|
refs/heads/master
| 2016-09-06T02:28:20.233312
| 2013-01-05T19:59:28
| 2013-01-05T19:59:28
| 7,311,793
| 0
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 415
|
h
|
texture.h
|
#ifndef TEXTURE_HH
#define TEXTURE_HH
#include <GL/gl.h>
/*
* A very basic texture handling class
*/
typedef class GLTextureclass{
public:
GLTextureclass();
~GLTextureclass();
int Load(const char* filename);
void Activate() {glBindTexture(GL_TEXTURE_2D,texture);}
//other options
void SetWrap(GLint mode);
void SetLinearFilter();
protected:
GLuint texture;
}GLTextureclass;
#endif
|
a21995f7f8be21b6fc245bec8a09dfe99557944c
|
aa1f91633d9b000d3d546e8a257f8bf4c8ff57b7
|
/src/videoserver.cpp
|
b3be6628c420cbd26a51f7a657151e7cbba31e5f
|
[] |
no_license
|
NASAKnights/deepspace-vision
|
54ad03614897fda89d3f665844374122a17f68f5
|
d78267936029e64db96320b0912d2782912571d7
|
refs/heads/master
| 2020-08-12T20:12:27.881092
| 2020-02-18T01:48:25
| 2020-02-18T01:48:25
| 214,832,654
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,664
|
cpp
|
videoserver.cpp
|
//#include "tcplib.h"
#include "tcp_thread.h"
#include <stdio.h>
#include <netdb.h>
#include <netinet/in.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <unistd.h>
extern int remoteSocket;
extern int videoPort;
extern int videoError;
void *videoServer(void *arg){
char host[80];
sprintf(host,"%s","127.0.0.1");
int sock = tcp_open_th(videoPort,host);
while(1){
int sockfd = tcp_listen_th(sock);
remoteSocket = sockfd;
/*
while (!sig_int){
int sockfd = tcp_listen();
printf("server accept the client...\n");
if(USESERVER){
int localSocket;
struct sockaddr_in localAddr, remoteAddr;
int addrLen= sizeof(struct sockaddr_in);
localSocket = socket(AF_INET,SOCK_STREAM,0);
if(localSocket == -1){
printf("error");
}
localAddr.sin_family = AF_INET;
localAddr.sin_addr.s_addr = INADDR_ANY;
localAddr.sin_port = htons( port );
if( bind(localSocket,(struct sockaddr *)&localAddr , sizeof(localAddr)) < 0) {
perror("Can't bind() socket");
exit(1);
}
//Listening
listen(localSocket , 3);
std::cout << "Waiting for connections...\n"
<< "Server Port:" << port << std::endl;
//accept connection from an incoming client
remoteSocket = accept(localSocket, (struct sockaddr *)&remoteAddr, (socklen_t*)&addrLen);
//std::cout << remoteSocket<< "32"<< std::endl;
if (remoteSocket < 0) {
perror("accept failed!");
exit(1);
}
}
}
*/
while(videoError==0) sleep(1);
close(remoteSocket);
remoteSocket=0;
videoError=0;
}
}
|
348d9d791262ad93fd8308542fa9a73d5d0c44c7
|
798a7aa9b1476efddbf948f442b60b1334a4b98c
|
/visiblepq.cc
|
44c4aae67d37c6ded8555b94a71386f4b1fff9d7
|
[] |
no_license
|
rivercheng/meshStreaming
|
75b26ba9abc709dcf62404286b193f77f1475921
|
a764c45f42368e18edff1caaaa200a5199b508af
|
refs/heads/master
| 2021-01-22T04:36:37.588905
| 2009-09-02T04:12:26
| 2009-09-02T04:12:26
| 298,125
| 2
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 4,130
|
cc
|
visiblepq.cc
|
#include "vertexid.hh"
#include "visiblepq.hh"
#include "Poco/RunnableAdapter.h"
#include "Poco/Mutex.h"
VisiblePQ::VisiblePQ(Ppmesh* ppmesh, Gfmesh* gfmesh)
:toContinue_(true), isStrict_(true), \
pixels_(0), size_(0) //ppmesh_(ppmesh), gfmesh_(gfmesh)
{
in_queue_ = new PQ();
out_queue_ = new PQ();
to_run_ = new Poco::RunnableAdapter<VisiblePQ>(*this, &VisiblePQ::run);
ppmesh_ = ppmesh;
gfmesh_ = gfmesh;
}
void VisiblePQ::stat_screen_area()
{
Gfmesh* gfmesh = gfmesh_;
//clear weight
gfmesh->clear_weight();
for (size_t i = 0; i < size_; i+=3)
{
unsigned char color_r = pixels_[i];
unsigned char color_g = pixels_[i+1];
unsigned char color_b = pixels_[i+2];
Index seq_no = color_r * 65536 + color_g*256 + color_b;
if (seq_no != 0)
{
gfmesh->increment_face_weight(seq_no-1);
}
if (!toContinue_) return;
//std::cerr<<(int)color_r<<" "<<(int)color_g<<" "<<(int)color_b<<" "<<seq_no<<std::endl;
}
for (size_t i = 0; i < gfmesh->face_number(); i++)
{
gfmesh->add_vertex_weight_in_face(i);
if (!toContinue_) return;
}
//for debug
/*
for (size_t i = 0; i<gfmesh->face_number(); i++)
{
std::cerr<<i<<" "<<gfmesh->face_weight(i)<<std::endl;
}*/
/*
for (size_t i = 0; i<gfmesh->vertex_number(); i++)
{
if (gfmesh->vertex_weight(i) != 0)
std::cerr<<i<<" "<<ppmesh_->index2id(i)<<" "<<gfmesh->vertex_weight(i)\
<<" "<<ppmesh_->idIsLeaf(ppmesh_->index2id(i))<<std::endl;
}
*/
}
void VisiblePQ::update(unsigned char* pixels, size_t size)
{
//toContinue_=false;
stoped_.lock();
pixels_ = pixels;
size_ = size;
toContinue_=true;
if (in_queue_) delete in_queue_;
in_queue_ = new PQ();
//weights.reset();
//std::cerr<<thread_pool_.available()<<" "<<thread_pool_.allocated()<<std::endl;
//thread_pool_.start(*to_run_);
run();
}
size_t VisiblePQ::pick(std::vector<VertexID>& id_array, size_t number)
{
size_t n = 0;
n = ppmesh_->pick(id_array, number);
//std::cerr<<"from to-be-split "<<n<<std::endl;
while (n<number)
{
VertexID id = pop();
if (id == 0)
{
//std::cerr<<"see 0. end. "<<std::endl;
break;
}
if (ppmesh_->isPicked(id))
{
//std::cerr<<id<<" picked"<<std::endl;
if (ppmesh_->idIsLeaf(id))
{
//std::cerr<<id<<" is leaf."<<std::endl;
}
continue;
}
id_array.push_back(id);
ppmesh_->set_picked(id);
n++;
}
return n;
}
VertexID VisiblePQ::pop()
{
VertexID top = 0;
if (!out_queue_->empty())
{
top = out_queue_->top();
assert(top!=0);
out_queue_->pop();
}
return top;
}
void VisiblePQ::run()
{
stat_screen_area();
//gfmesh_->reset_color();
std::vector<VertexID>::const_iterator it(ppmesh_->vertex_front().begin());
std::vector<VertexID>::const_iterator end(ppmesh_->vertex_front().end());
//std::cerr<<"vertex front size "<<ppmesh_->vertex_front().size()<<std::endl;
for (; it != end; ++it)
{
if (!toContinue_) break;
if (ppmesh_->idIsLeaf(*it)) continue;
if (ppmesh_->isPicked(*it)) continue;
/*if (ppmesh_->index2id(ppmesh_->id2index(*it)) != *it)
{
std::cerr<<*it<<" unmatch "<<ppmesh_->index2id(ppmesh_->id2index(*it))<<std::endl;
}
std::cerr<<"front"<<*it<<" "<<ppmesh_->id2index(*it)<<std::endl;*/
if (isStrict_)
{
if (gfmesh_->vertex_weight(ppmesh_->id2index(*it)) == 0) continue;
}
//std::cerr<<gfmesh_->vertex_weight(ppmesh_->id2index(*it))<<std::endl;
//gfmesh_->set_color(ppmesh_->id2index(*it), 0., 0., 1.);
push(*it);
}
PQ* temp = out_queue_;
out_queue_ = in_queue_;
in_queue_ = temp;
//std::cerr<<"out queue size "<<out_queue_->size()<<std::endl;
stoped_.unlock();
}
|
694784c0ca0b66d375b312538d66b92ee735e76e
|
d99077f33df72416148c99873284309112c6e190
|
/LaAbuelaContraatacaFINAL/src/MurcielagoPequeño.h
|
b711054b1edfb66dc1078de17d4877037f477195
|
[] |
no_license
|
raulherranzrodriguez/Gamedog
|
67d45dbf6b54bd276b50552482b00eea21df9938
|
e7e93510f3fff7770006a9c3587fd89ea8149c2a
|
refs/heads/main
| 2023-04-16T22:14:25.760935
| 2021-05-17T15:30:11
| 2021-05-17T15:30:11
| 363,188,266
| 0
| 0
| null | 2021-04-30T15:48:41
| 2021-04-30T15:48:40
| null |
ISO-8859-1
|
C++
| false
| false
| 136
|
h
|
MurcielagoPequeño.h
|
#pragma once
#include "Enemigo.h"
class MurcielagoPequeño: public Enemigo
{
public:
MurcielagoPequeño();
void volar();
};
|
6139b941f17feccf3811d1ee8448d4b026ae758d
|
c2d71f768b82d2da113f7a1699400ffb0f80eeaa
|
/translate2ds/directory.h
|
d30ed96561475459f496e6e78652db6ab0b00819
|
[
"Apache-2.0"
] |
permissive
|
NCAR/aircraft_oap
|
edc923be650adce7d14fd99ba443f0d064665b0c
|
ef39b97046aab15c6757e4f4a5c7dee55c4471cb
|
refs/heads/master
| 2023-09-03T15:18:50.751797
| 2023-08-19T21:31:39
| 2023-08-19T21:31:39
| 86,385,871
| 1
| 2
| null | 2022-03-21T15:47:23
| 2017-03-27T21:31:14
|
C++
|
UTF-8
|
C++
| false
| false
| 1,078
|
h
|
directory.h
|
#pragma once
#include <sys/stat.h>
#include <ftw.h>
#include "log.h"
namespace sp
{
void MakeDirectory(const std::string& name)
{
#ifdef _WIN32
std::string n = "mkdir " + name;
int result = system(n.c_str());
#else
int result = mkdir(name.c_str(), S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH);
#endif
if (result < 0)
{
g_Log << "Make Directory failed on \"" << name <<"\"\n";
}
}
int unlink_cb(const char *fpath, const struct stat *sb, int typeflag, struct FTW *ftwbuf)
{
int rv = remove(fpath);
if (rv)
perror(fpath);
return rv;
}
int rmrf(const char *path)
{
return nftw(path, unlink_cb, 64, FTW_DEPTH | FTW_PHYS);
}
void DeleteDirectory(const std::string& name)
{
#ifdef _WIN32
std::string n = "rmdir /s /q " + name;
int result = system(n.c_str()); //windows delete temp directory
// g_Log <<"WIN32\n";
#else
std::string n = "rm -rf " + name;
int result = rmrf(name.c_str());
// g_Log <<"NO WIN32\n";
#endif
if (result < 0)
{
g_Log << "Delete Directory failed on \"" << name <<"\" result =" << result << "\n";
}
}
}
|
4af782ab5398f2e8d4620348056ebb15257eeae3
|
4d25f97358a9d394c50d2969ac2b3525023ed12a
|
/rwmutex/rwmutex_sol.cpp
|
364d0e2b680f24416aff85d9ca07c1a9b8a30aa9
|
[] |
no_license
|
robryk/www10
|
11b092b45ed5f77686ec2812cd31b533d8dc96f6
|
af9d4ac9566e15a6b5c6f48496d4ef1eea5b9d3b
|
refs/heads/master
| 2016-09-06T00:26:52.219202
| 2014-08-21T07:57:53
| 2014-08-21T07:57:53
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,992
|
cpp
|
rwmutex_sol.cpp
|
#include <thread>
#include <mutex>
#include <iostream>
#include "bench.h"
#include <cassert>
#include <semaphore.h>
using namespace std;
constexpr int writer = 1<<20;
sem_t w_mutex;
sem_t r_sema;
sem_t w_sema;
atomic<int> count;
atomic<int> readers_remaining;
void init() {
assert(sem_init(&w_mutex, 0, 1) == 0);
assert(sem_init(&r_sema, 0, 0) == 0);
assert(sem_init(&w_sema, 0, 0) == 0);
count = 0;
readers_remaining = 0;
}
void destroy() {
assert(sem_destroy(&w_mutex) == 0);
assert(sem_destroy(&r_sema) == 0);
assert(sem_destroy(&w_sema) == 0);
}
void lock() {
sem_wait(&w_mutex);
int readers_inside = count.fetch_add(writer);
if (readers_remaining.fetch_add(readers_inside) != -readers_inside)
sem_wait(&w_sema);
}
void unlock() {
int readers_waiting = count.fetch_add(-writer) - writer;
for(int i=0;i<readers_waiting;i++)
sem_post(&r_sema);
sem_post(&w_mutex);
}
void rlock() {
int count_before = count.fetch_add(1);
if (count_before >= writer)
sem_wait(&r_sema);
}
void runlock() {
if (count.fetch_add(-1) >= writer) {
if (readers_remaining.fetch_add(-1) == 1)
sem_post(&w_sema);
}
}
atomic<int> tester;
void tester_thread(B* b, int read_count) {
while (!b->should_stop()) {
lock();
assert(tester.fetch_add(1<<20) == 0);
b->inc();
assert(tester.fetch_add(-(1<<20)) == (1<<20));
unlock();
for(int i=0;i<read_count;i++) {
rlock();
assert(tester.fetch_add(1) < (1<<20));
b->inc();
assert(tester.fetch_add(-1) < (1<<20));
runlock();
}
}
}
void bench_run(int n_threads, int read_count) {
thread thr[n_threads];
B b;
init();
tester = 0;
for(int i=0;i<n_threads;i++)
thr[i] = thread(&tester_thread, &b, read_count);
for(int i=0;i<n_threads;i++)
thr[i].join();
destroy();
cout << n_threads << " threads, " << read_count << " reads/write - " << b.report() << " ops/us\n";
}
int main() {
bench_run(1, 1);
bench_run(2, 0);
bench_run(2, 1);
bench_run(2, 5);
bench_run(4, 1);
bench_run(4, 5);
return 0;
}
|
23d0f8f9f395a56c4a674acc240564b21548c725
|
daeb47bfd7b8db78fb60914fcc31c13b641df46d
|
/openbr/plugins/cuda/cudal2.cpp
|
18231f8631ba61e6f2d18b30600903396ccee18b
|
[
"Apache-2.0"
] |
permissive
|
biometrics/openbr
|
a3a8d2f2302efce22a7310fe54d91ef1e2fc3fca
|
14279e43f9d196eb07def550067a4d0a222c0219
|
refs/heads/master
| 2023-08-28T18:26:23.021105
| 2023-08-24T19:41:37
| 2023-08-24T19:41:37
| 7,251,195
| 1,974
| 736
|
NOASSERTION
| 2023-08-24T19:41:38
| 2012-12-20T02:52:37
|
C++
|
UTF-8
|
C++
| false
| false
| 2,174
|
cpp
|
cudal2.cpp
|
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* Copyright 2016 Colin Heinzmann *
* *
* 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 <iostream>
using namespace std;
#include <openbr/plugins/openbr_internal.h>
// definitions from the CUDA source file
namespace br { namespace cuda { namespace L2 {
void wrapper(float const* aPtr, float const* bPtr, int length, float* outPtr);
}}}
namespace br
{
/*!
* \ingroup distances
* \brief L2 distance computed using eigen.
* \author Colin Heinzmann \cite DepthDeluxe
*/
class CUDAL2Distance : public UntrainableDistance
{
Q_OBJECT
float compare(const cv::Mat &a, const cv::Mat &b) const
{
if (a.type() != CV_32FC1 || b.type() != CV_32FC1) {
cout << "ERR: Type mismatch" << endl;
throw 0;
}
if (a.rows*a.cols != b.rows*b.cols) {
cout << "ERR: Dimension mismatch" << endl;
throw 1;
}
float out;
cuda::L2::wrapper(a.ptr<float>(), b.ptr<float>(), a.rows*a.cols, &out);
return out;
}
};
BR_REGISTER(Distance, CUDAL2Distance)
} // namespace br
#include "cuda/cudal2.moc"
|
5a55c573da66adee7342a9880656660eea24777c
|
4409388e421519dbd46fed6ab63b10a1e4fcc0f2
|
/ov/IR/VisitorSimC.h
|
b26c74b5b128734ea465db6766c7d5c7d2a6c826
|
[] |
no_license
|
alvinox/myOV
|
d477b7edd0fa4576de3c149ce35704cd34ff5bc6
|
aa2f25343a68290495fb00e9265ade8dbc5414bc
|
refs/heads/main
| 2023-02-17T21:19:53.277181
| 2020-12-30T07:05:32
| 2020-12-30T07:05:32
| 318,104,234
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 670
|
h
|
VisitorSimC.h
|
#ifndef _VISITOR_SIM_C_H_
#define _VISITOR_SIM_C_H_
#include "Visitor.h"
namespace ir {
class VisitorSimC final : public Visitor {
public:
static void Pass(Module* module);
public:
VisitorSimC()
: Visitor(SimulationC), lv(0) { }
public:
virtual void visit(Module* module) override;
virtual void visit(Design* design) override;
virtual void visit(Procedure* proc ) override;
virtual void visit(Register* reg ) override;
virtual void visit(Wire* wire ) override;
void IncrIndent() { lv++; }
void DecrIndent() { lv--; }
public:
unsigned lv;
std::stringstream ostr;
};
} // end namespace ir
#endif // _VISITOR_SIM_C_H_
|
e1c0d44031364c3a8a86042a1715c6b720168374
|
c4796cf63bd2cf6211b9dcf954eca212376194d1
|
/code/isTree.cpp
|
085ec43a98cf053a3173655d4125e60b995b0e7a
|
[
"MIT"
] |
permissive
|
MelihcanAkbulut/Graphs-Algortihms
|
bd390633ec5bd1562a349aa0e387a678b33a359c
|
064f54204e5dfb3d9d366317f28dfb74d0f44d60
|
refs/heads/main
| 2023-08-29T10:44:12.998572
| 2021-10-26T10:32:31
| 2021-10-26T10:32:31
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 5,804
|
cpp
|
isTree.cpp
|
#include <iostream>
#include<set>
using namespace std;
int edgeCount = 0;
int count1Degree = 0;
int komsuluk_matrisi[20][20];
int visitedN[20][20]={false};
// Grafi kontrol icin sirasiyla kolaydan zor olan isleme dogru sirasiyla islem yapilmistir.
// 1 - Kenar sayisi dugum sayisinin 1 eksigi kadardir.
// 2 - Bir agac icin en az 2 uc dugum olmasi gerekir.
// 3 - Döngü barindirmamasi gerekmektedir.
// bütün algoritma ve kodlari calisiyordur.
void countEdges(int src,int matrix[20][20]) // grafimizin kenar sayisi icin yazdigimiz fonksiyon
{
for(int i = 0; i < 20; i++)
{
if(visitedN[src][i] != false )
{
if(src != i)
{
if(matrix[src][i] != 0)
{
visitedN[src][i] = true;
visitedN[i][src] = true;
edgeCount = edgeCount + 1;
}
}
}
else
{
visitedN[src][i] = true;
visitedN[i][src] = true;
}
}
}
bool dfs(int vertex, set<int>&visited, int parent)
{
visited.insert(vertex);
for(int v = 0; v < 20; v++)
{
if(komsuluk_matrisi[vertex][v])
{
if(v == parent)
continue;
if(visited.find(v) != visited.end())
return true;
if(dfs(v, visited, vertex))
return true;
}
}
return false;
}
bool detectCycle() // cycle tespiti icin yazilan fonksiyon
{
set<int> visited;
for(int v = 0; v < 20; v++)
{
if(visited.find(v) != visited.end())
continue;
if(dfs(v, visited, -1))
{
return true;
}
}
return false;
}
int degree(int vertex, int A[20][20]) // dugumun derecesini bulmaya yarayan fonksiyonumuz
{
int deg = 0;
for(int i = 0; i < 20; i++)
{
if( A[vertex][i] == 1 )
deg = deg + 1;
}
return deg;
}
int main()
{
int dugumSayisi = 20;
int degrees[20];
int komsuluk_matrisi[20][20] = {
{
0,1,0,0,0,0,0,0,0,0,0,0,0,0,1,1,0,0,0,0 // 0. dügüm
},
{
1,0,1,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0 // 1. dugum
},
{
0,1,0,1,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0 // 2. düðüm
},
{
0,0,1,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0 // 3. düðüm
},
{
0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0 // 4. düðüm
},
{
0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0 // 5. düðüm
},
{
0,0,0,0,1,1,0,1,1,0,0,0,0,0,0,0,0,0,0,0 // 6. düðüm
},
{
0,0,0,0,0,0,1,0,1,0,0,0,0,0,0,0,0,0,0,0 // 7. düðüm
},
{
0,0,0,0,0,0,1,1,0,1,0,1,0,1,0,0,0,0,0,0 // 8. düðüm
},
{
0,0,0,1,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0 // 9. düðüm
},
{
0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0 // 10. düðüm
},
{
0,0,0,0,0,0,0,0,1,0,1,0,1,0,0,0,0,0,0,0 // 11. düðüm
},
{
0,0,0,0,0,0,0,0,0,0,0,1,0,1,0,0,0,0,0,0 // 12. düðüm
},
{
0,0,0,0,0,0,0,0,1,0,0,0,1,0,0,0,0,0,0,1 // 13. düðüm
},
{
1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0 // 14. düðüm
},
{
1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0 // 15. düðüm
},
{
0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,1,0 // 16. düðüm
},
{
0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,1,0 // 17. düðüm
},
{
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,0,1 // 18. düðüm
},
{
0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,1 // 19. düðüm
}
};
for(int i = 0; i < 4; i++) // verilen grafin agac olma durumu icin 3 özellik kontrol ettirdim 4 olma durumu agac olma durumudur.
{ // bu yüzden for döngüsü icine switch case yapisi kurdum
switch(i) // eger bir tane olmama durumu tespit edilirse döngü son bulur
{
case 1: // Bir agac icin ; kenar sayisinin bir fazlasi kadar dügüm vardir.
{
for(int i = 0; i < 20; i++)
{
countEdges(i,komsuluk_matrisi);
}
if (edgeCount + 1 != dugumSayisi )
{
cout<<"Verilen graf bir agac degildir. ||G|| + 1 = |G| sarti saglanmamaktadir. Kenar sayisi cok fazladir."<<endl;
}
break;
}
case 2: // Bir agac icin en az 2 uc dugum vardir.
{
for(int i = 0; i < 20; i++ )
{
degrees[i] = degree(i,komsuluk_matrisi);
if(degrees[i]==1)
{
count1Degree = count1Degree + 1;
}
}
if(count1Degree < 2)
{
cout<<"Verilen graf bir agac degildir. Cünkü en az 2 uc dugum yoktur."<<endl;
}
break;
}
case 3: // Bir grafin agac olmasi icin döngü barindirmamasi lazım
{
bool result;
result = detectCycle();
if(result)
{
cout <<"Verilen graf bir agac degildir. Cünkü döngü tespit edildi." << endl;
}
break;
}
case 4: // Grafin agac olma durumu
cout<<"Verilen graf bir agactir";
break;
}
}
return 0;
}
|
cdbcce39342abe0f72ac6c4c8040dea9d693f74a
|
c7398d1186085873c93c034f42f126c82d21b7e5
|
/workshop7/Product.cpp
|
81a9ab5bd5a94c7202fe71d0533911e508abf8f4
|
[] |
no_license
|
krn007/OOP345
|
3e08d50d523c387f7ba8d82230742f781b82e9de
|
fb0d285a62cebc41c910982e313723607ed58971
|
refs/heads/master
| 2020-03-25T00:50:39.098925
| 2018-08-01T21:09:51
| 2018-08-01T21:09:51
| 143,208,741
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 963
|
cpp
|
Product.cpp
|
/* OOP345 Workshop 7
Name - Karan Shah
Student_Id: 129965166
Date - 28th Decemeber 2017*/
#include <iomanip>
#include "Product.h"
#include "TaxableProduct.h"
using namespace std;
namespace w7 {
iProduct* readProduct(ifstream& in)
{
int pn;
double cost;
char ts;
in >> pn;
if (in.fail())
return (iProduct*)0;
in >> cost;
if (in.fail())
return (iProduct*)0;
ts = in.get();
if (ts != '\n') {
in >> ts;
return new TaxableProduct(pn, cost, ts);
}
else {
return new Product(pn, cost);
}
}
Product::Product(int product_number, double cost) {
product_number_ = product_number;
cost_ = cost;
}
double Product::getCharge() const {
return cost_;
}
void Product::display(std::ostream& os) const
{
os << setw(10) << product_number_ << fixed << setprecision(2);
os << setprecision(2) << setw(10) << cost_;
}
std::ostream& operator<<(std::ostream& os, const iProduct& P) {
P.display(os);
return os;
}
}
|
4d47c1220235ed6bbd1f892ec8e43a1e59eab367
|
63da17d9c6876e26c699dc084734d46686a2cb9e
|
/inf-6-exercise/01/Homework_ArraySkeleton.cpp
|
c7889fa45477748283d91c624f208d5da521cf55
|
[] |
no_license
|
semerdzhiev/oop-2020-21
|
0e069b1c09f61a3d5b240883cfe18f182e79bb04
|
b5285b9508285907045b5f3f042fc56c3ef34c26
|
refs/heads/main
| 2023-06-10T20:49:45.051924
| 2021-06-13T21:07:36
| 2021-06-13T21:07:36
| 338,046,214
| 18
| 17
| null | 2021-07-06T12:26:18
| 2021-02-11T14:06:18
|
C++
|
UTF-8
|
C++
| false
| false
| 2,717
|
cpp
|
Homework_ArraySkeleton.cpp
|
#include <cassert>
#include <iostream>
// dynamic array with a specified capacity and with certain number of elements (size)
// please consider why the input argument for the array is of type int*&?
// create a header file with the declarations of the functions,
// move the definitions to a .cpp file
// show how they are used in main.cpp
// allocate the memory
void allocateMemory(int*& array, size_t capacity)
{
}
// delete the allocated memory
void freeMemory(int*& array, size_t& size, size_t& capacity)
{
}
// reallocate memory with different capacity
bool reallocateMemory(int*& array, size_t size, size_t newCapacity)
{
}
// resize the array, if necessary
// double the size
bool resize(int*& array, size_t size, size_t& capacity)
{
}
// add element at the end of the array
// if the size is less than the capacity, the array should be resized
// resize the array, if necessary
bool addElement(int*& array, size_t& size, size_t& capacity, int newElem)
{
}
// add element at a specified position of the array
// resize if necessary
bool addElement(int*& array, size_t& size, size_t& capacity, int newElem, size_t position)
{
}
// print the elements of the array
void print(const int* array, size_t size, size_t capacity)
{
}
// remove the element at the specified position
// if the number of elements are less than 1/4 of the capacity,
// resize the array, use half of its capacity
bool removeElement(int*& array, size_t& size, size_t& capacity, size_t position)
{
}
int main()
{
// dynamic array that can be resized
int* array{ nullptr };
// capacity of the array
size_t capacity = 3;
// exact number of elements in the array
size_t size = 0;
allocateMemory(array, capacity);
addElement(array, size, capacity, 1);
addElement(array, size, capacity, 2);
addElement(array, size, capacity, 3);
std::cout << "The capacity of the array is " << capacity << std::endl;
std::cout << "The real count of the elements in the array is " << size << std::endl;
print(array, size, capacity);
addElement(array, size, capacity, 4, 2);
std::cout << "\nThe capacity of the array is " << capacity << std::endl;
std::cout << "The real count of the elements in the array is " << size << std::endl;
print(array, size, capacity);
removeElement(array, size, capacity, 0);
removeElement(array, size, capacity, 0);
removeElement(array, size, capacity, 0);
std::cout << "\nThe capacity of the array is " << capacity << std::endl;
std::cout << "The real count of the elements in the array is " << size << std::endl;
print(array, size, capacity);
freeMemory(array, size, capacity);
return 0;
}
|
454c001ac742a31c73c328ffa1cf5a035048a072
|
bdbbc611761582b173c08a2cae6a9a355feaee9a
|
/list_test1/test.cpp
|
830e67df08e5669a848c1431300cd95accbfd272
|
[] |
no_license
|
lssxfy123/C-study
|
a79f043fab25d597c3bc19748600857e3ee3f9de
|
e88632838251dfb3947d2dd95423c66f409ee80e
|
refs/heads/master
| 2022-02-05T02:30:46.475740
| 2022-01-23T14:00:59
| 2022-01-23T14:00:59
| 41,584,370
| 0
| 0
| null | null | null | null |
MacCentralEurope
|
C++
| false
| false
| 540
|
cpp
|
test.cpp
|
// Copyright 2015.
// author£ļŃűę|ę|
// ◊‘∂®“ŚList»›∆ų
#include <iostream>
#include <list>
using namespace std;
#include "List.hpp"
int main(int argc, char* argv[])
{
List<int> list1;
list1.push_back(1);
list1.push_back(2);
list1.push_back(3);
int k = list1.back();
cout << k << endl;
List<int>::const_iterator iter;
List<int> list2(list1);
for (iter = list2.begin(); iter != list2.end(); ++iter)
{
cout << *iter << ",";
}
cout << endl;
return 0;
}
|
f050f99998d05fa2377826ed7138cb682ad4d192
|
de99edf75d54e1a596bc1a8039299b9f03ba2513
|
/A/13/SSSP.cc
|
72b5e3f919185eedb042c5f11b447ad7b560df6f
|
[
"Unlicense"
] |
permissive
|
Menci/DataStructureAndAlgorithms
|
a082b8a43638cd8fad6c55c617e6208c2f36111a
|
e5d773bd927e83f72dc0c1579e48469200f31620
|
refs/heads/master
| 2020-09-21T06:25:50.477619
| 2020-03-31T00:26:51
| 2020-03-31T00:26:51
| 224,709,080
| 0
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 4,284
|
cc
|
SSSP.cc
|
#include <fstream>
#include <iostream>
#include <functional>
#include <vector>
#include <chrono>
#include <limits>
#include <queue>
#include "FibonacciHeap.h"
struct Node {
size_t id;
// adjacency list
struct Edge *firstEdge = nullptr;
// for common sssp
int dist, distAnswer;
// for dijkstra
FibonacciHeap<std::pair<int, Node *>>::NodeProxy nodeInFibonacciHeap;
// for spfa
bool enqueued;
int relaxationCount;
// for johnson
int h;
};
std::vector<Node> nodes;
struct Edge {
Node *from, *to;
int w;
Edge *next;
};
size_t addNode() {
size_t i = nodes.size();
nodes.push_back(Node{i});
return i;
}
void addEdge(int u, int v, int w) {
nodes[u].firstEdge = new Edge{&nodes[u], &nodes[v], w, nodes[u].firstEdge};
}
bool spfa(Node *start) {
for (auto &node : nodes) {
node.dist = std::numeric_limits<int>::max();
node.enqueued = false;
node.relaxationCount = 0;
}
std::queue<Node *> queue;
start->dist = 0;
start->enqueued = true;
queue.push(start);
while (!queue.empty()) {
Node *v = queue.front();
queue.pop();
v->enqueued = false;
for (Edge *e = v->firstEdge; e; e = e->next) {
if (e->to->dist > v->dist + e->w) {
e->to->dist = v->dist + e->w;
e->to->relaxationCount++;
// negative circle
if (e->to->relaxationCount > nodes.size()) {
return false;
}
if (!e->to->enqueued) {
e->to->enqueued = true;
queue.push(e->to);
}
}
}
}
return true;
}
void dijkstra(Node *start) {
for (auto &node : nodes) {
node.dist = std::numeric_limits<int>::max();
}
FibonacciHeap<std::pair<int, Node *>> heap;
start->dist = 0;
for (auto &node : nodes) {
node.nodeInFibonacciHeap = heap.push(std::make_pair(node.dist, &node));
}
while (!heap.empty()) {
auto pair = heap.getMin().getKey();
heap.deleteMin();
Node *v = pair.second;
for (Edge *e = v->firstEdge; e; e = e->next) {
if (e->to->dist > v->dist + e->w) {
e->to->dist = v->dist + e->w;
e->to->nodeInFibonacciHeap.decreaseKey(std::make_pair(e->to->dist, e->to));
}
}
}
}
bool johnson() {
size_t extra = addNode();
for (size_t i = 0; i < nodes.size() - 1; i++) addEdge(extra, i, 0);
if (!spfa(&nodes[extra])) return false;
for (auto &node : nodes) node.h = node.dist;
for (auto &node : nodes) {
for (Edge *e = node.firstEdge, **p = &node.firstEdge; e; ) {
if (e->from->id == extra || e->to->id == extra) {
// edges for johnson: delete it
Edge *tmp = e;
e = *p = e->next;
delete tmp;
} else {
// edges in origin graph: transform it
e->w = e->w + e->from->dist - e->to->dist;
assert(e->w >= 0);
p = &e->next;
e = e->next;
}
}
}
nodes.pop_back();
return true;
}
void measureTime(std::string actionName, std::function<void ()> function) {
auto startTime = std::chrono::high_resolution_clock::now();
function();
auto endTime = std::chrono::high_resolution_clock::now();
double timeElapsed = std::chrono::duration_cast<std::chrono::milliseconds>(endTime - startTime).count();
std::cerr << actionName << " costs " << timeElapsed / 1000 << "s" << std::endl;
}
int main() {
int n, m;
std::cin >> n >> m;
for (int i = 0; i < n; i++) addNode();
while (m--) {
int u, v, w;
std::cin >> u >> v >> w;
addEdge(u, v, w);
}
bool noCheck = false;
for (auto &node : nodes) {
if (!(std::cin >> node.distAnswer)) {
noCheck = true;
break;
}
}
measureTime("Bellman-Ford (SPFA)", []() {
if (!spfa(&nodes[0])) std::cerr << "Bellman-Ford: negative circle found" << std::endl;;
});
if (!noCheck)
for (auto &node : nodes) assert(node.dist == node.distAnswer);
measureTime("Johnson + Dijkstra", []() {
bool negativeCircle;
measureTime("Johnson", [&]() {
negativeCircle = !johnson();
if (negativeCircle) std::cerr << "Johnson: negative circle found" << std::endl;
});
if (!negativeCircle) {
measureTime("Dijkstra", []() {
dijkstra(&nodes[0]);
});
for (auto &node : nodes) node.dist = node.dist + node.h - nodes[0].h;
}
});
if (!noCheck)
for (auto &node : nodes) assert(node.dist == node.distAnswer);
}
|
fcbece1dac00a299add765761e243bbb3b918bf2
|
5dc8f9ad01ab7f82773a7cd3b2107b63d729a25a
|
/Linked Helper/linkedlist.cpp
|
c15b1bf5c19014fa286155d3a352be1a2af5cf53
|
[] |
no_license
|
chp2001/Linked-Helper
|
e3de6b26d943687324cd5a92fbb5e0c5790715c1
|
9df64c252e16d8b8e8cbce77b2b3dfb79c8ea26b
|
refs/heads/master
| 2023-08-02T02:40:24.658191
| 2021-10-04T15:06:39
| 2021-10-04T15:06:39
| 412,565,651
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 12,728
|
cpp
|
linkedlist.cpp
|
#include <iostream>
#include <fstream>
#include <sstream>
#include <iomanip>
#include <string>
#include <cctype>
using namespace std;
#include <chrono>
#include <ctime>
class Node {
public:
string name;
int data;
Node* next;
Node(string s);
Node(int i);
Node();
};
Node::Node(string s) {
name = s;
next = NULL;
}
Node::Node(int i) {
name = "";
data = i;
next = NULL;
}
Node::Node() {
name = "";
next = NULL;
}
Node* newNode(int i) {
Node* newptr = new Node(i);
return newptr;
}
class Array {
public:
string name;
Node* head;
Node* end;
int cacheLn;
bool cached;
Node* cacheCall;
int cacheIndex;
bool unchanged;
bool collected;
Node** collect;
Array(string s);
Array(Node* n);
Array();
Node* endOfList();
Node* index(int i);
int len();
void add(Node* n);
bool del(int i);
bool del_(int i);//behind scenes, don't use directly
bool insert(Node* n, int i);
bool insert_(Node* n, int i);
bool swapIndexes(int i, int j);
bool swapIndexes_(int i, int j);
void denote_change();
void change_at_index(int i);
void change_at_index_add(int i, int n);
void do_collect();
};
Array::Array(string s) {
name = s;
head = NULL;
end = NULL;
cacheLn = 0;
unchanged = true;
collected = false;
}
Array::Array(Node* n) {
name = "";
head = n;
end = n;
cacheLn = 1;
unchanged = true;
collected = false;
}
Array::Array() {
name = "";
head = NULL;
end = NULL;
cacheLn = 0;
unchanged = true;
collected = false;
}
Node* Array::endOfList() {
if (head == NULL) {
return NULL;
}
else {
return end;
}
}
Node* Array::index(int i) {
if (head == NULL or len()<i+1) {
return NULL;
}
else if (collected) {
return collect[i];
}
else if (cached and cacheIndex < i) {
Node* handler = cacheCall;
int j = cacheIndex;
while (handler->next != NULL) {
if (j == i) {
break;
}
handler = handler->next;
j++;
}
if (j == i) {
cacheIndex = i;
cacheCall = handler;
return handler;
}
else {
return NULL;
}
}
else {
Node* handler = head;
int j = 0;
while (handler->next != NULL) {
if (j == i) {
break;
}
handler = handler->next;
j++;
}
if (j == i) {
cacheIndex = i;
cacheCall = handler;
cached = true;
return handler;
}
else {
return NULL;
}
}
}
void Array::denote_change() {
unchanged = false;
if (collected) {
delete collect;
}
collected = false;
cached = false;
}
void Array::change_at_index(int i) {
unchanged = false;
if (collected) {
Node** oldcollect = collect;
int length = len();
collect = new Node*[length];
for (int j = 0;j < i;j++) {
collect[j] = oldcollect[j];
}
Node* handler = collect[i - 1];
int j = i - 1;
while (handler->next != NULL) {
handler = handler->next;
collect[j] = handler;
j++;
}
}
cached = false;
//hashed = false;
}
void Array::change_at_index_add(int i, int n) {
cacheLn+=n;
if (collected) {
Node** oldcollect = collect;
int length = len();
collect = new Node * [length];
for (int j = 0;j < i;j++) {
collect[j] = oldcollect[j];
}
Node* handler = collect[i - 1];
int j = i - 1;
while (handler->next != NULL) {
handler = handler->next;
collect[j] = handler;
j++;
}
}
cached = false;
unchanged = true;
}
int Array::len() {
if (head == NULL) {
return 0;
}
else {
if (unchanged) {
return cacheLn;
}
Node* handler = head;
int i = 1;
while (handler->next != NULL) {
handler = handler->next;
i++;
}
cacheLn = i;
unchanged = true;
return i;
}
}
void Array::add(Node* n) {
if (head == NULL) {
head = n;
end = n;
}
else {
end->next = n;
end = n;
}
change_at_index_add(cacheLn,1);
}
bool Array::del(int i) {
if (del_(i)) {
change_at_index_add(i,-1);
return true;
}
else {
return false;
}
}
bool Array::del_(int i) {
int length = len();
if (head == NULL or length <= i) {
return false;
}
else {
if (length == 1) {//if we are deleting the head, and there are no other items, aka none before or after
delete index(0);
head = NULL;
return true;
}
Node* before = head;
Node* deathrow = head;
Node* handler = head;
Node* after = NULL;
if (i == 0) {//if we are deleting the head, aka none before, some after
deathrow = head;
handler = head->next;
delete deathrow;
head = handler;
return true;
}
if (length == i + 1) {//if our item is at the end of the list, aka none after, some before
before = index(i - 1);
deathrow = before->next;
delete deathrow;
before->next = NULL;
end = before;
return true;
}
if (length > i + 1) {//if there is an item both before and after our target
before = index(i - 1);
deathrow = before->next;
handler = deathrow->next;
delete deathrow;
before->next = handler;
return true;
}
}
}
bool Array::insert(Node* n, int i) {
if (insert_(n, i)) {
change_at_index_add(i,1);
return true;
}
else {
return false;
}
}
bool Array::insert_(Node* n, int i) {
int length = len();
if (length==i) {//adding at end of list is easy!
add(n);
return true;
}
if (head == NULL or length <= i) {//we won't insert if there aren't enough terms, or we are trying to add at an index beyond the end
return false;
}
else {
Node* before = head;
Node* handler = head;
Node* after = NULL;
if (i == 0) {//if we are inserting at the head, aka none before, some after
handler = head;
head = n;
head->next = handler;
return true;
}
if (length >= i + 1) {//middle of the list
before = index(i - 1);
handler = before->next;
n->next = handler;
before->next = n;
return true;
}
}
return false;
}
bool Array::swapIndexes(int i, int j) {
if (i > j) {
int temp = j;
j = i;
i = temp;
}
if (swapIndexes_(i,j)) {
change_at_index_add(i,0);
return true;
}
else {
return false;
}
}
bool Array::swapIndexes_(int i, int j) {
int length = len();
if (length <= i or length <= j or i==j) {
return false;
}
if (j == i + 1) {
if (i == 0) {
Node* n1 = index(i);
Node* n2 = index(j);
head = n2;
n1->next = n2->next;
n2->next = n1;
return true;
}
else {
Node* n1;
Node* n2;
Node* before = index(i - 1);
n1 = before->next;
n2 = n1->next;
before->next = n2;
n1->next = n2->next;
n2->next = n1;
return true;
}
}
else {
Node* b1;
Node* b2 = index(j - 1);
Node* n1;
if (i > 0) {
b1 = index(i - 1);
n1 = b1->next;
}
else {
b1 = NULL;
n1 = index(i);
}
Node* n2 = b2->next;
Node* a1 = n1->next;
Node* a2 = n2->next;
if (i > 0) {
b1->next = n2;
}
else {
head = n2;
}
if (a2 == NULL) {
end = n1;
}
b2->next = n1;
n2->next = a1;
n1->next = a2;
return true;
}
return false;
}
void Array::do_collect() {
collect = new Node*[len()];
Node* handler = head;
for (int i = 0;i < len();i++) {
collect[i] = handler;
handler = handler->next;
}
collected = true;
}
Array* newArray(string s) {
Array* newptr = new Array(s);
return newptr;
}
double curtime() {
auto nanoseconds = std::chrono::duration_cast<std::chrono::nanoseconds>(std::chrono::system_clock::now().time_since_epoch()).count();
return (double)nanoseconds* 1e-9;
}
int main(int argc, char* argv[]) {
srand(time(NULL));
double beforetime = curtime();
double offset = curtime() - beforetime;
printf_s("getting curtime took %f seconds\n", offset);
offset = 0;
Array* mainList = newArray("main");
beforetime = curtime();
for (int i = 0;i < 60000;i++) {
mainList->add(newNode(60000-i));
}
double after = curtime();
printf_s("adding %d terms took %f seconds\n", mainList->len(), after - beforetime-offset);
beforetime = curtime();
for (int i = 0;i < 35;i++) {
mainList->del(0);
}
printf_s("deleting 35 terms took %f seconds\n", curtime() - beforetime-offset);
int j = 0;
beforetime = curtime();
for (int i = 0;i < 35;i++) {
mainList->del(rand() % mainList->len());
//printf_s("%d ", mainList->index(i)->data);
j++;
}
after = curtime();
printf_s("deleting %d RANDOM terms took %f seconds\n", j, after - beforetime - offset);
beforetime = curtime();
int curlen = mainList->len();
if (0) {
for (int i = 0;i < mainList->len() / 2;i++) {
int curlen = mainList->len();
if (not mainList->insert(newNode(1337), 2 * i + 1)) {
printf_s(" failed at %d when length was %d, attempted to insert at %d\n", i, curlen, 2 * i + 1);
}
else {
//printf_s("succeeded at %d when length was %d, inserted at %d\n", i, curlen, 2 * i + 1);
}
}
}
after = curtime();
printf_s("inserting %d terms took %f seconds\n",mainList->len()-curlen, after - beforetime-offset);
j = 0;
beforetime = curtime();
for (int i = 0;i < mainList->len();i++,j++) {
if (j >= 10) {
//printf_s("\n");
j = 0;
}
auto data = mainList->index(i)->data;
//printf_s("%d ", mainList->index(i)->data);
}
after = curtime();
printf_s("calling all %d terms took %f seconds\n",mainList->len(), after - beforetime - offset);
beforetime = curtime();
j = 0;
for (int i = 0;i < mainList->len();i++) {
auto data = mainList->index(rand()%mainList->len())->data;
//printf_s("%d ", mainList->index(i)->data);
j++;
}
after = curtime();
printf_s("calling %d RANDOM terms took %f seconds\n",j, after - beforetime - offset);
//printf_s("\nvalue at index 3 is %d\n",mainList->index(3)->data);
curlen = mainList->len();
beforetime = curtime();
if (1) {
for (int i = 0;i < curlen;i++) {
int curlen = mainList->len();
if ((mainList->len() - i - 1!=i) and not mainList->swapIndexes(i, mainList->len() - i - 1)) {
printf_s(" failed at %d when length was %d, attempted to swap at %d\n", i, curlen, mainList->len() - i - 1);
}
else {
//printf_s("succeeded at %d when length was %d, swapped at %d\n", i, curlen, mainList->len() - i);
}
}
}
after = curtime();
printf_s("swapping all %d terms took %f seconds\n", mainList->len(), after - beforetime - offset);
beforetime = curtime();
mainList->do_collect();
after = curtime();
printf_s("collecting all %d terms took %f seconds\n", mainList->len(), after - beforetime - offset);
beforetime = curtime();
for (int i = 0;i <mainList->len();i++, j++) {
if (j >= 10) {
//printf_s("\n");
j = 0;
}
auto data = mainList->index(i)->data;
//printf_s("%d ", mainList->index(i)->data);
}
after = curtime();
printf_s("calling all %d terms from collected array took %f seconds\n", mainList->len(), after - beforetime - offset);
return 0;
}
|
2878a2ab17e5ae5a4440f3f9c54c4872c9fd4ec0
|
9ab6c262492e61cbde7e92511a4669f4eab34159
|
/Homework5Q1/Homework5Q1/Source.cpp
|
f3c8fefcd3a32f6116bd8935dadc25ff39ad6ee2
|
[] |
no_license
|
YosefSchoen/IntroToProgramming
|
54087c19fc86ce12337fe75ebfb80fa25007beb3
|
58c032a0cf45d567dfaf913b68e9cd677c3f67e2
|
refs/heads/master
| 2020-07-30T20:45:01.923464
| 2019-09-23T12:44:05
| 2019-09-23T12:44:05
| 210,351,836
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 950
|
cpp
|
Source.cpp
|
/*
Homework 5
This program will tell you the area of a rectangle and a circle.
Introduction to Computer Science.
Question 1.
Yosef Schoen
22/11/17
*/
#include <iostream>
using namespace std;
// function for area of a rectangle
int area(int x, int y) {
return x * y;
}
// function for area of a circle
float area(int x) {
return x * x * 3.14159;
}
int main() {
int length;
int width;
int radius;
cout << "enter length and width of the rectangle:\n";
cin >> length >> width;
//not allowing negative lengths
while (length <= 0 || width <= 0) {
cout << "ERROR\n";
cin >> length >> width;
}
// calling the function for are of a rectangle
cout << area(length, width) << endl;
cout << "enter radius of the circle:\n";
cin >> radius;
// not allowing negative lengths
while (radius <= 0) {
cout << "ERROR\n";
cin >> radius;
}
// calling function for area of a circle
cout << area(radius) << endl;
return 0;
}
|
ad09dbe88ed7cf162caaebebe734efbf634f697e
|
6b40e9dccf2edc767c44df3acd9b626fcd586b4d
|
/NT/inetsrv/iis/setup/urlscan/main.cpp
|
4871955e2e753fd5e73d9bc6520db31730562f52
|
[] |
no_license
|
jjzhang166/WinNT5_src_20201004
|
712894fcf94fb82c49e5cd09d719da00740e0436
|
b2db264153b80fbb91ef5fc9f57b387e223dbfc2
|
refs/heads/Win2K3
| 2023-08-12T01:31:59.670176
| 2021-10-14T15:14:37
| 2021-10-14T15:14:37
| 586,134,273
| 1
| 0
| null | 2023-01-07T03:47:45
| 2023-01-07T03:47:44
| null |
UTF-8
|
C++
| false
| false
| 5,034
|
cpp
|
main.cpp
|
/*++
Copyright (c) 2001 Microsoft Corporation
Module Name :
updurls2.cpp
Abstract:
The main for the Project
Author:
Christopher Achille (cachille)
Project:
URLScan Update
Revision History:
March 2002: Created
--*/
// updurls2.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include "windows.h"
#include "urlscan.h"
#include "resource.h"
BOOL CheckParameters( int argc, _TCHAR* argv[], BOOL *bQuietMode, BOOL *bExpandOnly );
// ShowMessage
//
// Show either a warning or a message to the user
//
// Parameters:
// dwMessageId - The id of the message
// bError - TRUE == error, FALSE == informative
//
// This does not return anything, because there would be no
// point. By this time we have failed or not, and there
// is not additional way to notify the user
//
void ShowMessage( DWORD dwMessageId, BOOL bError )
{
HMODULE hModule = GetModuleHandle( NULL );
TCHAR szMessage[MAX_PATH];
TCHAR szTitle[MAX_PATH];
if ( hModule == NULL )
{
// Could not get handle to module
return;
}
if ( !LoadString( hModule, dwMessageId, szMessage, MAX_PATH ) )
{
// Failed to Retrieve Message
return;
}
if ( !LoadString( hModule, IDS_TITLEBAR, szTitle, MAX_PATH ) )
{
// Failed to Retrieve Title
return;
}
MessageBox( NULL, szMessage, szTitle, MB_OK | ( bError ? MB_ICONEXCLAMATION : MB_ICONINFORMATION ) );
}
// ShowText
//
// Show text out to the console
//
// Parameters:
// dwMessageId - The id of the message
// szExeName - The name of this executable
//
// This does not return anything, because there would be no
// point. By this time we have failed or not, and there
// is not additional way to notify the user
//
void ShowText( DWORD dwMessageId, LPWSTR szExeName )
{
HMODULE hModule = GetModuleHandle( NULL );
TCHAR szMessage[MAX_PATH];
if ( hModule == NULL )
{
// Could not get handle to module
return;
}
if ( !LoadString( hModule, dwMessageId, szMessage, MAX_PATH ) )
{
// Failed to Retrieve Message
return;
}
wprintf(szMessage, szExeName);
}
// UrlScanUpdate
//
// Update the URLScan files
DWORD
UrlScanUpdate()
{
TCHAR szUrlScanPath[ MAX_PATH ];
DWORD dwErr;
if ( !IsAdministrator() )
{
return IDS_ERROR_ADMIN;
}
if ( !IsUrlScanInstalled( szUrlScanPath, MAX_PATH ) )
{
return IDS_ERROR_NOTINSTALLED;
}
dwErr = InstallURLScanFix( szUrlScanPath );
if ( dwErr != ERROR_SUCCESS )
{
// Failure, IDS resource should be returned
return dwErr;
}
// This is very cosmetic thing, so we do not want to
// fail for this reason
UpdateRegistryforAddRemove();
// Success
return IDS_SUCCESS_UPDATE;
}
// CheckParameters
//
// Check Parameters for command line flags
//
// Parameters:
// argc - [in] Number of arguments
// argv - [in] The list of arguments
// bQuietMode - [out] Is Quiet Mode Turned On?
// bExpandOnly - [out] Is Expand Only turned on?
//
// Return values:
// TRUE - Read Parameters without a problem
// FALSE - Failed to read parameters
//
BOOL
CheckParameters( int argc, _TCHAR* argv[], BOOL *bQuietMode, BOOL *bExpandOnly )
{
DWORD dwCount;
// SET Defaults
*bQuietMode = FALSE;
*bExpandOnly = FALSE;
for ( dwCount = 1; dwCount < (DWORD) argc; dwCount ++ )
{
if ( ( argv[ dwCount ][0] != '/' ) ||
( argv[ dwCount ][1] == '\0' ) ||
( argv[ dwCount ][2] != '\0' )
)
{
return FALSE;
}
// Because if previous "if", command must be in the form "/x\0" where
// x is any character but '\0'
switch ( argv[ dwCount ][1] )
{
case 'x':
case 'X':
*bExpandOnly = TRUE;
break;
case 'q':
case 'Q':
*bQuietMode = TRUE;
break;
default:
return FALSE;
break;
}
}
return TRUE;
}
int __cdecl wmain(int argc, _TCHAR* argv[])
{
BOOL bExpandOnly;
BOOL bQuietMode;
BOOL bRet = TRUE;
DWORD dwErr;
if ( !CheckParameters( argc, argv, &bQuietMode, &bExpandOnly ) )
{
ShowText( IDS_USAGE, ( argv && argv[0] ) ? argv[0] :
URLSCAN_UPDATE_DEFAULT_NAME );
return 1;
}
if ( bExpandOnly )
{
// Only Expansion is wanted, so only do that.
if ( ExtractUrlScanFile( URLSCAN_DEFAULT_FILENAME ) )
{
dwErr = IDS_SUCCESS_EXTRACT;
}
else
{
dwErr = IDS_ERROR_EXTRACT;
}
}
else
{
dwErr = UrlScanUpdate();
}
bRet = ( dwErr == IDS_SUCCESS_EXTRACT ) ||
( dwErr == IDS_SUCCESS_UPDATE );
if ( !bQuietMode )
{
ShowMessage( dwErr, !bRet );
}
// Return 0 or 1 depending on if there is an error or not
return bRet ? 0 : 1;
}
|
09be69a41a7417b7ec948ddf7b6ef720890032f3
|
5dc1b25bf593af2fc4e7d08174d807e5253c1e81
|
/PhoneBook/HumanInfo.cpp
|
e8a16d973853a34bb8b2be5ff3ea0d91e9cddbdc
|
[] |
no_license
|
alexkikos/Cplus_Phone_Book_Class
|
0cad9b82ca1903c183cbcc3cd070423caf7b406a
|
9c6470676e07d0c5819dc2242159f3373603c0ea
|
refs/heads/master
| 2020-09-26T06:35:00.076575
| 2019-12-05T21:15:51
| 2019-12-05T21:15:51
| 226,190,375
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,171
|
cpp
|
HumanInfo.cpp
|
#include "HumanInfo.h"
bool HumanInfo::SetName(string name1)
{
if (name1.size() != 0 and name1.size() < 15) name = name1;
else
{
cout << "\nWrong input";
return false;
}
return true;
}
bool HumanInfo::SetPtronymic(string name1)
{
if (name1.size() != 0 and name1.size() < 20) patronymic = name1;
else
{
cout << "\nWrong input";
return false;
}
return true;
}
bool HumanInfo::SetSurname(string n)
{
if (n.size() != 0 and n.size() < 20) surname = n;
else
{
cout << "\nWrong input";
return false;
}
return true;
}
bool HumanInfo::SetHomePhone(string n)
{
if (n.size() != 0 and n.size() < 20)
{
home_phone = n;
}
else
{
cout << "\nWrong input";
return false;
}
return true;
}
bool HumanInfo::SetWorkPhone(string n)
{
if (n.size() != 0 and n.size() < 15)
{
work_phone = n;
}
else
{
cout << "\nWrong input";
return false;
}
return true;
}
bool HumanInfo::SetAdditionalInfo(string s)
{
if (s.size() != 0 and s.size() < 20) additional_info = s;
else
{
cout << "\nWrong input";
return false;
}
return true;
}
string HumanInfo::GetName()
{
return name;
}
string HumanInfo::Getpatronymic()
{
return patronymic;
}
string HumanInfo::GetSurname()
{
return surname;
}
string HumanInfo::GetHomePhone()
{
return home_phone;
}
string HumanInfo::GetWorkPhone()
{
return work_phone;
}
string HumanInfo::GetAdditionalInfo()
{
return additional_info;
}
void HumanInfo::ShowAllInfo()
{
cout << GetName();
cout << setw(26 - GetName().size()) << Getpatronymic();
cout << setw(26 - Getpatronymic().size()) << GetSurname();
cout << setw(28) << GetWorkPhone();
cout << setw(24) << GetHomePhone();
cout << setw(13) << GetAdditionalInfo() << endl;
}
HumanInfo::HumanInfo(string name1, string patronymic1, string surname1, string home_phone1, string work_phone1, string addinfo)
{
this->SetName(name1);
this->SetPtronymic(patronymic1);
this->SetSurname(surname1);
this->SetHomePhone(home_phone1);
this->SetWorkPhone(work_phone1);
this->SetAdditionalInfo(addinfo);
}
|
bb80a632c83a0910415d14c5271ff1612197d5de
|
d22d811448d72582959cb772b00f93802b09e77f
|
/cpp/exercise2.cpp
|
a0e3c6f593336fadfef350092b820d10c71b5f56
|
[] |
no_license
|
gitmo/uni
|
2ef915d93d47a1d51747a384544c85c397da9985
|
008dc7e1d3df2bfbbe5564e4dff163d0285014aa
|
refs/heads/master
| 2021-01-22T04:33:41.304995
| 2011-10-14T11:49:32
| 2011-10-14T11:49:32
| 1,078,070
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 968
|
cpp
|
exercise2.cpp
|
//
// exercise2.cpp
// C++ Course Exercises
//
// Created by gitmo on 11.10.11.
// Copyright 2011 Team Awesome. All rights reserved.
//
#include <iostream>
#include <cstring>
#include "exercise2.h"
char lower (char c) {
if( 'A' <= c && c <= 'Z' )
return c + 'a' - 'A';
return c;
}
bool reverse (char str[]) {
bool palindrom = true;
size_t n = 0;
size_t len = strlen(str);
for (size_t i = len; i > len / 2 ; i--) {
char c = str[i - 1];
str[i - 1] = lower(str[n]);
str[n] = lower(c);
if (str[n] != str[i - 1])
palindrom = false;
n++;
}
return palindrom;
}
void test(const char * s)
{
char str[strlen(s) + 1];
strcpy(str, s);
std::cout << str << '\n';
if (reverse(str))
std::cout << "Palindrom!" << std::endl;
std::cout << str << std::endl;
}
int main (int argc, const char * argv[])
{
test("Hamster");
test("Anna");
return 0;
}
|
039502e7cc03ba65440dc9dede62e613e627ce51
|
3d0541f0aa9ba6322150f5aa4b293e3170470b36
|
/traceuint.h
|
3835032e300214458240b9d628988e7f7d90f0cb
|
[] |
no_license
|
tomasvdw/tracebit
|
300479f32d704bef2d9778b7c859384ff71db4f5
|
2d41b758ad80f1a65519862bf12b813d8e159b6e
|
refs/heads/master
| 2020-04-02T07:58:12.469876
| 2016-06-19T16:13:46
| 2016-06-19T16:13:46
| 61,488,068
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 5,229
|
h
|
traceuint.h
|
#ifndef TRACEBIT
#define TRACEBIT
#include <set>
#include <iostream>
class TraceBit;
#define ZERO TraceBit()
#define ONE TraceBit(0)
#define MIN(x,y) ((x) < (y) ? (x) : (y))
#include "tracebit_mod2.h"
//#include "tracebit_opcount.h"
template<int N, typename T>
class TraceUint;
typedef TraceUint<8, unsigned char> Tuint8;
typedef TraceUint<16, unsigned short> Tuint16;
typedef TraceUint<32, unsigned int> Tuint32;
typedef TraceUint<64, unsigned long long> Tuint64;
/* Template that defines a 1 to 8 byte integer using tracing bits
* The type of tracing is defined by the include above
* N = the number of bits
* T = the underlying unit type
*/
template<int N, typename T>
class TraceUint {
public:
TraceBit bits[N];
TraceUint()
{
}
// Initialize from the underlying uint type
TraceUint(const T& value)
{
for(int n =0; n < N; n++)
{
if (((value >> n) & 1) == 1)
bits[n] = ONE;
else
bits[n] = ZERO;
}
}
// Returns the underlying uint value
// Only possible if this contains no variable references
T Value() const {
T res = 0;
for(int n=0; n < N; n++)
{
int v = bits[n].Value();
if (v == 1)
res |= (1 << n);
else if (v <0)
throw "Can't create value from expression";
}
return res;
}
// Casting
// We're doing this unchecked
operator Tuint8() const {
Tuint8 result;
for(int n=0; n < 8; n++)
result.bits[n] = bits[n];
return result;
}
operator Tuint16() const {
Tuint16 result;
for(int n=0; n < MIN(16,N); n++)
result.bits[n] = bits[n];
return result;
}
operator Tuint32() const {
Tuint32 result;
for(int n=0; n < MIN(32,N); n++)
result.bits[n] = bits[n];
return result;
}
operator Tuint64() const {
Tuint64 result;
for(int n=0; n < MIN(64,N); n++)
result.bits[n] = bits[n];
return result;
}
// replaces a bit with a variable
// variable should be 1-15 refered to as x1 to x15
void SetVariable(int bit, int variable)
{
bits[bit] = TraceBit(variable);
}
// define bitwise operators
TraceUint operator&(const TraceUint &other) const {
TraceUint result = TraceUint();
for(int n=0; n < N; n++)
result.bits[n] = this->bits[n] & other.bits[n];
return result;
}
TraceUint operator|(const TraceUint &other) const {
TraceUint result = TraceUint();
for(int n=0; n < N; n++)
result.bits[n] = this->bits[n] | other.bits[n];
return result;
}
TraceUint operator^(const TraceUint &other) const {
TraceUint result = TraceUint();
for(int n=0; n < N; n++)
result.bits[n] = this->bits[n] ^ other.bits[n];
return result;
}
TraceUint operator>>(const int shift) const {
TraceUint result = TraceUint();
for(int n=0; n < (N-shift); n++)
result.bits[n] = this->bits[n + shift];
return result;
}
TraceUint operator<<(const int shift) const {
TraceUint result = TraceUint();
for(int n=shift; n < N; n++)
result.bits[n] = this->bits[n - shift];
return result;
}
TraceUint operator~() const {
TraceUint result = TraceUint();
for(int n=0; n < N; n++)
{
result.bits[n] = ~this->bits[n];
}
return result;
}
TraceUint operator+(const TraceUint &other) const {
TraceUint result = TraceUint();
// we need to apply the binary adder
TraceBit carry = ZERO;
for(int n=0; n < N; n++)
{
result.bits[n] = (this->bits[n] ^ other.bits[n])
^ carry;
carry = (this->bits[n] & other.bits[n])
| (carry & (this->bits[n] ^ other.bits[n]));
}
return result;
}
};
// Stream implementation
// Creates a binary-string with the content,
// embedding formulas where needed
template<int N, typename T>
std::ostream& operator<<(std::ostream& os, const TraceUint<N, T>& obj)
{
for(int n=N-1; n >=0; n--)
{
os << obj.bits[n].to_str();
}
return os;
}
// helper function for direct packing
static void tracebit_pack(Tuint32 *target, const Tuint8 * source)
{
for(int n=0;n<8; n++)
target->bits[n] = source[3].bits[n];
for(int n=0;n<8; n++)
target->bits[n+8] = source[2].bits[n];
for(int n=0;n<8; n++)
target->bits[n+16] = source[1].bits[n];
for(int n=0;n<8; n++)
target->bits[n+24] = source[0].bits[n];
}
static void tracebit_unpack(Tuint8 *target, const Tuint32 source)
{
for(int n=0;n<8; n++)
target[3].bits[n] = source.bits[n];
for(int n=0;n<8; n++)
target[2].bits[n] = source.bits[n+8];
for(int n=0;n<8; n++)
target[1].bits[n] = source.bits[n+16];
for(int n=0;n<8; n++)
target[0].bits[n] = source.bits[n+24];
}
#endif // TRACEBIT
//#define TEST_TRACEBIT
|
18be151f8cd5c164f48427cca98fb0704dd4b648
|
b62f51e8ccc4a75ee20d879dc761d360301891c7
|
/meshes/rgbcube.cpp
|
12944e89272cb12fff4189dd01975764662f71d1
|
[] |
no_license
|
mistler/opengl
|
5b5042a16f4f627d0ee9bc7fec216e1d92f9cf0b
|
5fb1120b213d310105200960d1311ee5398a16c7
|
refs/heads/master
| 2016-09-06T06:10:18.973453
| 2015-12-06T13:32:21
| 2015-12-06T13:32:21
| 42,841,431
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,080
|
cpp
|
rgbcube.cpp
|
#include "meshes/rgbcube.h"
RgbCube::RgbCube(): Mesh(){
cubeVertexArray = new GLfloat[24]{0.0, 0.0, 1.0,
0.0, 1.0, 1.0,
1.0, 1.0, 1.0,
1.0, 0.0, 1.0,
0.0, 0.0, 0.0,
0.0, 1.0, 0.0,
1.0, 1.0, 0.0,
1.0, 0.0, 0.0};
cubeColorArray = new GLfloat[24]{0.0, 0.0, 1.0,
0.0, 1.0, 1.0,
0.0, 0.0, 0.0,
1.0, 0.0, 1.0,
1.0, 1.0, 1.0,
0.0, 1.0, 0.0,
1.0, 1.0, 0.0,
1.0, 0.0, 0.0};
cubeIndexArray = new GLubyte[24]{0,3,2,1,
0,1,5,4,
7,4,5,6,
3,7,6,2,
1,2,6,5,
0,4,7,3};
}
void RgbCube::render(QOpenGLShaderProgram *program){
//glVertexPointer(3, GL_FLOAT, 0, cubeVertexArray);
//glColorPointer(3, GL_FLOAT, 0, cubeColorArray);
glDrawElements(GL_QUADS, 24, GL_UNSIGNED_BYTE, cubeIndexArray);
}
RgbCube::~RgbCube(){
delete[] cubeVertexArray;
delete[] cubeColorArray;
delete[] cubeIndexArray;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.