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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
7ff95159104c0bcd7e43c8a1bcafdf4341135f1b | 4a0c7284d3737a285eda472b46dbf7ffffd3186b | /packages/remote/src/Broker.h | d8e1c88cc64624d9d7c6f7d88769fd56813405ec | [
"Unlicense"
] | permissive | russellholt/gf-rsl2 | 3f8e3971b02580cdc5ae4dcaf891db601082de14 | bf38ccad74af73519bbdb40b0f945bba4d95dcf3 | refs/heads/master | 2016-08-05T09:42:07.368005 | 2013-10-27T18:33:12 | 2013-10-27T18:33:12 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,070 | h | Broker.h | #include <rw/cstring.h>
#include <rw/ctoken.h>
#include "NetAddress.h"
#ifndef _Broker_H_
#define _Broker_H_
/**
* A broker is represented by a name and network address.
*
* $Id: Broker.h,v 1.1 1998/11/17 23:11:19 toddm Exp $
*/
class Broker
{
public:
/**
* This broker's identifier.
*/
RWCString name;
/**
* This broker's network address.
*/
NetAddress *addr;
/**
* Constructs a broker.
*
* Params:
* brkName - the broker's name
* brkAddr - the broker's network address
*/
Broker (const RWCString &brkName, const NetAddress &brkAddr):
name (brkName) { addr = new NetAddress (brkAddr); }
/**
* Constructs a broker from the given string.
*
* Params:
* strBroker - the string, e.g., "B1=horizon:3838"
*/
Broker (const RWCString &strBroker) { RWCTokenizer st (strBroker);
name = st ("=");
addr = new NetAddress (st ("=")); }
/**
* Destroys a broker.
*/
~Broker () { delete addr; }
};
#endif
|
6c3ba60edfca5992489228a9a9ca3cb723017156 | e2fb29d0c7d938d93fc7cc7b7299a6614ea7a721 | /src/dist_clustering/tests/simple_algo_test.cc | 0d8a22269e50fc476083edc82acb781eb1bd0412 | [
"MIT"
] | permissive | nkkarpov/StreamingCC | 18d48136ee6d15bfd40107a0f0802a0da66b5127 | d8bf04c0914873cc92d881dbc098e955c185744a | refs/heads/master | 2020-04-24T16:24:49.439499 | 2019-07-08T15:37:42 | 2019-07-08T15:37:42 | 172,105,159 | 0 | 0 | null | 2019-02-22T17:17:15 | 2019-02-22T17:17:15 | null | UTF-8 | C++ | false | false | 1,618 | cc | simple_algo_test.cc | #include "../algorithms/simple_algo.h"
#include "../algorithms/algo_util.h"
#include "../experiments/dataManager.h"
#define ARMA_DONT_USE_WRAPPER
#include "../arma/include/armadillo"
#include "../lest.hpp"
const lest::test specification[] = {
CASE("RandomClustering"){ClusteringInput input;
ClusteringOutput output;
input.n_centers = 10;
for (int i = 0; i < 100; ++i) {
arma::vec v(5);
v.fill(i);
input.data.push_back(v);
}
input.n_outliers = 5;
RandomClustering algo;
algo.perform(input, output);
EXPECT(output.centers.size() == input.n_centers);
EXPECT(output.outliers_indices.size() == input.n_outliers);
}
,
/*
CASE("ArmaKmeansClustering") {
ClusteringInput input;
ClusteringOutput output;
input.n_centers = 10;
for (int i = 0; i < 100; ++i) {
arma::vec v(5);
v.fill(i);
input.data.push_back(v);
}
input.n_outliers = 5;
ArmaKmeansClustering algo;
algo.n_iter=10;
algo.perform(input, output);
EXPECT( output.centers.size() == input.n_centers );
EXPECT( output.outliers_indices.size() == input.n_outliers );
},
*/
CASE("ArmaKmeansClustering") {
ClusteringInput input;
ClusteringOutput output;
DataSet dataSet;
dataSet.name = "16points";
dataSet.load();
input.n_centers = 4;
input.n_outliers = 0;
input.data = dataSet.data;
ArmaKmeansClustering algo;
algo.n_iter = 10;
algo.perform(input, output);
EXPECT(output.centers.size() == input.n_centers);
EXPECT(output.outliers_indices.size() == input.n_outliers);
}
}
;
int main() { return lest::run(specification); }
|
1ca4f970dae0b132a4722fad77aca64d4caddb13 | 3f7028cc89a79582266a19acbde0d6b066a568de | /source/extensions/filters/http/original_src/original_src.cc | a4ef7d19aa50e1ad9ea2b39eec74a400253d6a7d | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | envoyproxy/envoy | 882d3c7f316bf755889fb628bee514bb2f6f66f0 | 72f129d273fa32f49581db3abbaf4b62e3e3703c | refs/heads/main | 2023-08-31T09:20:01.278000 | 2023-08-31T08:58:36 | 2023-08-31T08:58:36 | 65,214,191 | 21,404 | 4,756 | Apache-2.0 | 2023-09-14T21:56:37 | 2016-08-08T15:07:24 | C++ | UTF-8 | C++ | false | false | 1,708 | cc | original_src.cc | #include "source/extensions/filters/http/original_src/original_src.h"
#include "source/common/common/assert.h"
#include "source/extensions/filters/common/original_src/socket_option_factory.h"
namespace Envoy {
namespace Extensions {
namespace HttpFilters {
namespace OriginalSrc {
OriginalSrcFilter::OriginalSrcFilter(const Config& config) : config_(config) {}
void OriginalSrcFilter::onDestroy() {}
Http::FilterHeadersStatus OriginalSrcFilter::decodeHeaders(Http::RequestHeaderMap&, bool) {
const auto downstream_address =
callbacks_->streamInfo().downstreamAddressProvider().remoteAddress();
ASSERT(downstream_address);
if (downstream_address->type() != Network::Address::Type::Ip) {
// Nothing we can do with this.
return Http::FilterHeadersStatus::Continue;
}
ENVOY_LOG(debug,
"Got a new connection in the original_src filter for address {}. Marking with {}",
downstream_address->asString(), config_.mark());
const auto options_to_add = Filters::Common::OriginalSrc::buildOriginalSrcOptions(
std::move(downstream_address), config_.mark());
callbacks_->addUpstreamSocketOptions(options_to_add);
return Http::FilterHeadersStatus::Continue;
}
Http::FilterDataStatus OriginalSrcFilter::decodeData(Buffer::Instance&, bool) {
return Http::FilterDataStatus::Continue;
}
Http::FilterTrailersStatus OriginalSrcFilter::decodeTrailers(Http::RequestTrailerMap&) {
return Http::FilterTrailersStatus::Continue;
}
void OriginalSrcFilter::setDecoderFilterCallbacks(Http::StreamDecoderFilterCallbacks& callbacks) {
callbacks_ = &callbacks;
}
} // namespace OriginalSrc
} // namespace HttpFilters
} // namespace Extensions
} // namespace Envoy
|
2357f31447b37b1e6130b0f1383a4756a0cb4c3a | 465f1f7bd7dd287eb1e53ce79d986caf941aaeb9 | /38. Count and Say.cpp | 56d2f9d21343a2d69d909766ff60ca05afd00c1d | [] | no_license | gurjotsingh4398/Leetcode-solution | 21a70c5e094961e6e5f9ef89f731835126c42a43 | 7594c3a0167819799a6e09a63717df3b18851bd8 | refs/heads/master | 2020-04-20T20:39:52.144743 | 2019-10-06T09:55:56 | 2019-10-06T09:55:56 | 169,083,362 | 2 | 2 | null | 2019-10-06T09:55:57 | 2019-02-04T13:34:58 | C++ | UTF-8 | C++ | false | false | 442 | cpp | 38. Count and Say.cpp | // https://leetcode.com/problems/count-and-say/
class Solution {
public:
string countAndSay(int n) {
if(n==1) return "1";
string s = countAndSay(n-1);
string ans = "";
for(int i=0;i<s.size();i++){
int count=1;
while(i<s.size()-1 && s[i]==s[i+1]) {
i++; count++;
}
ans.append(to_string(count) + s[i]);
}
return ans;
}
};
|
b0cd9e461d1a77d4df574ef14a3011d95daa58a6 | 5402c124c79e7c851568e8509fef2da8f9a85e2e | /crc.cpp | ca21903ddafac571a6752054fea63474343d69af | [] | no_license | sawood14012/cnlab | 4e2328cef3f47e7b03aa23215db45e330a8f771b | db85e563b48472fcd2dd932335d5c483a020375f | refs/heads/master | 2020-04-14T06:19:57.384592 | 2018-12-31T23:44:32 | 2018-12-31T23:44:32 | 163,683,347 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 925 | cpp | crc.cpp | #include<iostream>
#include<string>
using namespace std;
int crc(char *ip,char *op,char *poly,int mode){
strcpy(op,ip);
if(mode){
for(int i=1;i<strlen(poly);i++)
strcat(op,"0");
}
for(int i=0;i<strlen(ip);i++)
{
if (op[i]=='1'){
for(int j=0;j<strlen(poly);j++)
{
if(op[i+j]==poly[j])
op[i+j]='0';
else
op[i+j]='1';
}
}
}
for(int i=0;i<strlen(op);i++)
if(op[i]=='1')
return 0;
return 1;
}
int main(){
char ip[50],op[50],recv[50];
char poly[]="10001000000100001";
cout << "Enter the input message in binary"<< endl;
cin >> ip;
crc(ip, op, poly, 1);
cout << "The transmitted message is: " << ip << op + strlen(ip) << endl;
cout << "Enter the recevied message in binary" << endl;
cin >> recv;
if (crc(recv, op, poly, 0))
cout << "No error in data" << endl;
else
cout << "Error in data transmission has occurred" << endl;
return 0;
}
|
443a38bde2642dcf3ecc778f3eb3c950c9738c07 | ed86df060b2f55f68254e3006f0378fdcb35d2bb | /CommonIncludes.hpp | 7c50e7ed648c684e6beb43753b350b144ef8b284 | [
"MIT"
] | permissive | YukiWorkshop/libevdevPlus | 437a33ae5de7802381319c62dd4cce6805e7361f | cb3ca40ad6a13b62e51fef35384cc895f04353b7 | refs/heads/master | 2022-02-13T00:59:50.643285 | 2021-06-07T16:48:54 | 2021-06-07T16:48:54 | 163,064,864 | 8 | 9 | MIT | 2022-01-29T23:00:06 | 2018-12-25T08:47:20 | C++ | UTF-8 | C++ | false | false | 843 | hpp | CommonIncludes.hpp | /*
This file is part of libevdevPlus.
Copyright (C) 2018-2021 Reimu NotMoe <reimu@sudomaker.com>
This program is free software: you can redistribute it and/or modify
it under the terms of the MIT License.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
*/
#pragma once
#include <set>
#include <unordered_set>
#include <unordered_map>
#include <string>
#include <vector>
#include <iostream>
#include <exception>
#include <system_error>
#include <initializer_list>
#include <cmath>
#include <ctime>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cinttypes>
#include <fcntl.h>
#include <unistd.h>
#include <linux/input.h>
#include <linux/input-event-codes.h>
|
aeecbe2ecb0c5326f055a21f7a936b3e599868d8 | 30d86944adba5d7d54dc7714ee91925152f17091 | /otros_aed/Estructuras de Datos I/Compress/binarizacion.cpp | 22fa2d707ff61ba6e29a3a88417292a64899fa0f | [] | no_license | luigy-mach/aed | 835209bedebc575235ee881935c68fc4c7073a23 | 008a6b9d12c58985730acef1a7990c6e2a1147ab | refs/heads/master | 2021-05-04T21:14:13.727062 | 2018-02-03T16:49:50 | 2018-02-03T16:49:50 | 119,912,383 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,575 | cpp | binarizacion.cpp | #include "binarizacion.h"
void binarizacion::binarizar(string file)
{
fil=col=256;
imagename=file;
CImg<unsigned char> image(imagename.c_str());
//image.display();
unsigned char * vec =image.get_vector();
int tope=120;
int cont=0;
int cont2=0;
for(int i=0;i<256*256;i++)
{
float r=((int)vec[i]*0.3)+((int)vec[(i+(256*256*1))]*0.59)+((int)vec[(i+(256*256*2))]*0.11);
if(r<tope)
r=0;
else
{
r=1;
}
if(cont<=255)
{
if(cont2==256)
{
cont++;
cont2=0;
}
if(r==1) mimatriz(cont,cont2)=r;
cont2++;
}
}
}
void binarizacion::print()
{
mimatriz.Print();
}
MatrizE<int,256,256> binarizacion::getMatriz()
{
return mimatriz;
}
void binarizacion::savePGM(string archivo)
{
ofstream image(archivo.c_str());
image<<"P2"<<endl;
image<<fil<<" "<<col<<endl;
NodoE<int> ** p;
for(int i=0;i<256;i++)
{
for(int j=0;j<256;j++)
{
if(mimatriz.find_fil(i,j,p))
image<<255<<endl;
else
{
image<<0<<endl;
}
}
}
}
void binarizacion::load_binarizacion(string file)
{
CImg<unsigned char> image(file.c_str());
image.save_png("binarizado.png");
}
void binarizacion::mostrar_img(string name)
{
fil=col=256;
imagename=name;
CImg<unsigned char> image(imagename.c_str());
image.save_png("nuevo.png");
}
|
86e1eef74f8fb30b790ee58f928fcbb8c2bcb4b2 | e2c5be00034a72ebff70e57b999a68390dad546f | /gists/synth.ino | 740b8f226cf7ee8b926d2a845ceb481add3627cf | [] | no_license | tandav/dotfiles | 4d589c4310486e9956735dc33796aea67cf9c919 | ed87fe1c65e53d8114a4773baa0a73c5131c2745 | refs/heads/master | 2023-07-06T23:43:06.168222 | 2023-06-17T08:33:38 | 2023-06-17T08:33:38 | 142,873,028 | 3 | 0 | null | 2023-07-23T13:26:06 | 2018-07-30T12:35:16 | Python | UTF-8 | C++ | false | false | 1,038 | ino | synth.ino | #include <DueTimer.h>
#include <SineWaveDue.h>
float Sa = 1200; // base note frequency (Sa)
int bar = 2000; // bar length in ms
int _16 = bar / 16;
int melody[] = { 0, 1, 3, 5, 7, 8, 10, 12 };
float note(float semitone) {
return Sa * pow(2, semitone / 12);
}
void setup() {
analogReadResolution(10);
analogWriteResolution(10);
// pinMode(9, OUTPUT);
Serial.begin(9600);
}
void loop() {
for (int i = 0; i < 8; i++) {
sw.playTone(note(melody[i]), _16);
delay(_16);
sw.playTone(Sa, _16);
delay(_16);
// Serial.println(note(i));
// Serial.println(1/12);
// sw.playTone2(Sa, note(i), 1000);
// delay(1000);
}
// sw.playTone(2000);
// delay(1000);
// sw.stopTone();
// sw.playTone2(1000, 1200);
// delay(1000);
// sw.stopTone();
// sw.playTone(5000, 1000);
// for( int i; i<10; i++){
// digitalWrite(9, HIGH);
// sw.playToneDecay(400, .1*i);
// delay(1000);
// digitalWrite(9, LOW);
// delay(100);
// }
}
|
692153bdb0a727254f9a99507be2553d1d4ce6b6 | 901571e54db419ccd0aa4d7a3dbfcd8dd5b37207 | /Algorithm_study_yechan/Binary Search Tree/Implement_C++/tree.h | 042ce95ddbc6b22a99733f1441625bdb2c4a3f2c | [] | no_license | fbdp1202/AlgorithmParty | 3b7ae486b4a27f49d2d40efd48ed9a45a98c77e8 | 9fe654aa49392cb261e1b53c995dbb33216c6a20 | refs/heads/master | 2021-08-03T22:52:30.182103 | 2021-07-22T06:15:45 | 2021-07-22T06:15:45 | 156,948,821 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,904 | h | tree.h | #include <iostream>
#include <functional>
#include "node.h"
using namespace std;
template <typename T>
class BinarySearchTree {
private:
Node<T>* root;
public:
BinarySearchTree<T>();
~BinarySearchTree<T>();
bool search(T value, function<int(T&, T&)>& comp);
bool remove(T value, function<int(T&, T&)>& comp);
bool internal_remove(Node<T>*& current, T value, function<int(T&, T&)>& comp);
bool insert(T value, function<int(T&, T&)>& f);
bool internal_insert(Node<T>*& current, T value, function<int(T&, T&)>& f);
Node<T>*& find_left_most_child(Node<T>*& current);
void replace_node(Node<T>*& replaced, Node<T>*& newone);
void traverse_pre_order(function<void(T&)>& f);
void internal_traverse_pre_order(Node<T>* current, function<void(T&)>& f);
void traverse_in_order(function<void(T&)>& f);
void internal_traverse_in_order(Node<T>* current, function<void(T&)>& f);
void traverse_post_order(function<void(T&)>& f);
void internal_traverse_post_order(Node<T>* current, function<void(T&)>& f);
bool is_empty(void);
};
template <typename T>
BinarySearchTree<T>::BinarySearchTree() {
root = nullptr;
}
template <typename T>
BinarySearchTree<T>::~BinarySearchTree() {
delete root;
}
template <typename T>
bool BinarySearchTree<T>::search(T value, function<int(T&, T&)>& comp)
{
Node<T>* current = root;
while (current) {
if (comp(current->data, value) == 0) {
return true;
} else if (comp(value, current->data) == 1) {
current = current->right;
} else {
current = current->left;
}
}
return false;
}
template <typename T>
Node<T>*& BinarySearchTree<T>::find_left_most_child(Node<T>*& current) {
while(current->left) {
current = current->left;
}
return current;
}
template <typename T>
void BinarySearchTree<T>::replace_node(Node<T>*& replaced, Node<T>*& newone) {
if (replaced == nullptr || newone == nullptr) {
return;
}
if (replaced->left != nullptr && replaced->right != nullptr) {
newone->left = replaced->left;
if(replaced->right != newone)
newone->right = replaced->right;
}
Node<T>* temp = replaced;
replaced = newone;
delete temp;
return;
}
template <typename T>
bool BinarySearchTree<T>::remove(T value, function<int(T&, T&)>& comp)
{
return internal_remove(root, value, comp);
}
template <typename T>
bool BinarySearchTree<T>::internal_remove(Node<T>*& current, T value,
function<int(T&, T&)>& comp) {
if (comp(current->data, value) == 0) {
if (current->left == nullptr && current->right == nullptr) {
// if leaf node,
delete current;
current = nullptr;
} else if (current->left != nullptr && current->right != nullptr) {
// if has two children
replace_node(current, find_left_most_child(current->right));
} else if (current->left != nullptr && current->right == nullptr) {
// only has a left child;
replace_node(current, current->left);
} else if (current->left == nullptr && current->right != nullptr) {
// only has a right child
replace_node(current, current->right);
}
return true;
} else if (comp(value, current->data) == 1) {
// if the variable value is greater than current node's data
return internal_remove(current->right, value, comp);
} else {
// if the variable value is less than current node's data
return internal_remove(current->left, value, comp);
}
return false;
}
template <typename T>
bool BinarySearchTree<T>::insert(T value, function<int(T&, T&)>& comp) {
return internal_insert(root, value, comp);
}
template <typename T>
bool BinarySearchTree<T>::internal_insert(Node<T>*& current, T value,
function<int(T&, T&)>& comp)
{
// recursive
if (current == nullptr) {
current = new Node<T>(value);
return true;
} else if (comp(current->data, value) == 1) {
// if the variable current is greater than value,
return internal_insert(current->left, value, comp);
} else if (comp(current->data, value) == -1) {
// if the variable current is less than value,
return internal_insert(current->right, value, comp);
}
// duplicated
return false;
}
template <typename T>
void BinarySearchTree<T>::traverse_pre_order(function<void(T&)>& printer)
{
// depth-first traversal
internal_traverse_pre_order(root, printer);
}
template <typename T>
void BinarySearchTree<T>::internal_traverse_pre_order(Node<T>* current,
function<void(T&)>& f) {
if (current == nullptr) {
return;
}
f(current->data);
internal_traverse_pre_order(current->left, f);
internal_traverse_pre_order(current->right, f);
}
template <typename T>
void BinarySearchTree<T>::traverse_in_order(function<void(T&)>& printer)
{
// depth-first traversal
internal_traverse_in_order(root, printer);
}
template <typename T>
void BinarySearchTree<T>::internal_traverse_in_order(Node<T>* current,
function<void(T&)>& f) {
if (current == nullptr) {
return;
}
internal_traverse_in_order(current->left, f);
f(current->data);
internal_traverse_in_order(current->right, f);
}
template <typename T>
void BinarySearchTree<T>::traverse_post_order(function<void(T&)>& printer)
{
// depth-first traversal
internal_traverse_post_order(root, printer);
}
template <typename T>
void BinarySearchTree<T>::internal_traverse_post_order(Node<T>* current,
function<void(T&)>& f) {
if (current == nullptr) {
return;
}
internal_traverse_post_order(current->left, f);
internal_traverse_post_order(current->right, f);
f(current->data);
}
template <typename T>
bool BinarySearchTree<T>::is_empty(void)
{
if (root == nullptr)
return false;
return true;
} |
05d175640f2ebfb06c790228f89d7ba04b28774a | 4b9418e3f535ccd551b02e86c5b699127d77233f | /packages/spatial_discretization/Inverse_Multiquadric_RBF.cc | c929ecf928a684c213a4aa0206a5f498cd92bc35 | [] | no_license | brbass/yak | 2e4352218a48fb2c77998026e5f9f6748d109da9 | ef3654139ca6590278917951ebc8418545a9addf | refs/heads/master | 2022-12-22T13:59:58.710252 | 2022-12-14T19:29:32 | 2022-12-14T19:29:32 | 56,200,793 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,063 | cc | Inverse_Multiquadric_RBF.cc | #include "Inverse_Multiquadric_RBF.hh"
#include <cmath>
Inverse_Multiquadric_RBF::
Inverse_Multiquadric_RBF(int number_of_dimensions,
vector<double> const &position,
vector<double> const &shape_parameter):
RBF(number_of_dimensions,
position,
shape_parameter)
{
}
double Inverse_Multiquadric_RBF::
basis(vector<double> const &r) const
{
double dist2 = get_distance_squared(r);
return 1 / sqrt(1 + dist2);
}
double Inverse_Multiquadric_RBF::
dbasis(int dim,
vector<double> const &r) const
{
double dist2 = get_distance_squared(r);
double kr2 = shape_[dim] * shape_[dim] * (r[dim] - position_[dim]);
return -kr2 * pow(1 + dist2, -1.5);
}
double Inverse_Multiquadric_RBF::
ddbasis(int dim,
vector<double> const &r) const
{
double dist2 = get_distance_squared(r);
double distdim = r[dim] - position_[dim];
double k2r2 = shape_[dim] * shape_[dim] * distdim * distdim;
return shape_[dim] * shape_[dim] * (1 + dist2 - 3 * k2r2) * pow(1 + dist2, -2.5);
}
|
1f969117562e97b98a08fafa41b64d19f9463100 | 10b57a1d41b6bf47e5e9b480251a9e085fbbb322 | /cpp03/ex04/SuperTrap.hpp | ba5b57b149298ac38ff8cf97ca725a4eef2c9cc5 | [] | no_license | matgj/piscine_cplusplus | 441a08301f0227a9912b5402821376c53cea65a7 | 88e626e17124fbc00af14ecb17f307fd7bdd95ad | refs/heads/main | 2023-04-12T08:06:36.818325 | 2021-04-09T02:48:52 | 2021-04-09T02:48:52 | 356,112,085 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,436 | hpp | SuperTrap.hpp | /* ************************************************************************** */
/* */
/* ::: :::::::: */
/* SuperTrap.hpp :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: Mathis <Mathis@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2020/11/11 10:37:33 by Mathis #+# #+# */
/* Updated: 2020/11/11 12:40:54 by Mathis ### ########.fr */
/* */
/* ************************************************************************** */
#ifndef SUPERTRAP_HPP
# define SUPERTRAP_HPP
# define RESET "\x1B[0m"
# define BOLD "\x1B[1m"
# define RED "\x1B[31m"
# define GREEN "\x1B[32m"
# define BLUE "\x1B[34m"
# include <iostream>
# include <string>
# include "NinjaTrap.hpp"
class SuperTrap : public FragTrap, public NinjaTrap
{
public:
SuperTrap();
~SuperTrap();
SuperTrap(std::string name);
SuperTrap(const SuperTrap ©);
SuperTrap &operator=(const SuperTrap ©);
void meleeAttack(std::string const &arget);
void rangedAttack(std::string const &target);
};
#endif
|
b8d565641e428becf50a9cd4876a7715a889ae6b | eee8adf2c5745d8cb250be5972134ad433e54789 | /GameMap.cpp | 75e0d0e8da6a90259942c067ab8ae27e062c29a4 | [] | no_license | SpiritedAwayCN/SokoBan | 32de2bec41cc7b5a69d262a8eb04ed96c3a4b19a | e95b14c45a63d16e05ad595e28ad09ce9ad07a12 | refs/heads/master | 2020-04-24T03:06:05.752220 | 2019-03-17T13:14:34 | 2019-03-17T13:14:34 | 171,659,768 | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 7,844 | cpp | GameMap.cpp | #include "system.h"
#include<algorithm>
#include<iostream>
void GameMap::update_box(short *box_data, short player_x, short player_y) {
memset(current_map, 0, sizeof(current_map));
//重载地图
for (short i = Map_uper - 1; i <= Map_uper + Map_length; i++)
for (short j = Map_left - 1; j <= Map_left + Map_width; j++)
current_map[i][j] = Game_Wall[i][j] ? 1 : 0;
for (short i = 0; i < Goals_num; i++) {
box_data[i] >>= 4;
current_map[box_data[i] / (MAX_LEN - 2) + 1][box_data[i] % (MAX_LEN - 2) + 1] = i + 2;//地图数字=箱子id+2
box_data[i] <<= 4;
}
find_way(box_data, player_x, player_y);
std::sort(box_data, box_data + Goals_num);//完成后排序
}
void GameMap::update_rev_box(short *box_data, short player_x, short player_y, bool clr = true){
if(clr)
memset(current_map, 0, sizeof(current_map));
//重载地图
for (short i = Map_uper - 1; i <= Map_uper + Map_length; i++)
for (short j = Map_left - 1; j <= Map_left + Map_width; j++)
if(current_map[i][j] != -1)
current_map[i][j] = Game_Wall[i][j] ? 1 : 0;
for (short i = 0; i < Goals_num; i++) {
box_data[i] >>= 4;
current_map[box_data[i] / (MAX_LEN - 2) + 1][box_data[i] % (MAX_LEN - 2) + 1] = i + 2;//地图数字=箱子id+2
box_data[i] <<= 4;
}
find_rev(box_data, player_x, player_y);
std::sort(box_data, box_data + Goals_num);//完成后排序
}
void GameMap::find_rev(short *box_data, short x, short y) {
current_map[x][y] = -1;//标记已经走过
if (current_map[x - 1][y] > 1 && current_map[x + 1][y] <= 0)
box_data[current_map[x - 1][y] - 2] |= 1 << 3;//上一步up
if (!current_map[x - 1][y])
find_rev(box_data, x - 1, y);
if (current_map[x + 1][y] > 1 && current_map[x - 1][y] <= 0)
box_data[current_map[x + 1][y] - 2] |= 1 << 2;//down
if (!current_map[x + 1][y])
find_rev(box_data, x + 1, y);
if (current_map[x][y - 1] > 1 && current_map[x][y + 1] <= 0)
box_data[current_map[x][y - 1] - 2] |= 1 << 1;//left
if (!current_map[x][y - 1])
find_rev(box_data, x, y - 1);
if (current_map[x][y + 1] > 1 && current_map[x][y - 1] <= 0)
box_data[current_map[x][y + 1] - 2] |= 1;//right
if (!current_map[x][y + 1])
find_rev(box_data, x, y + 1);
}
void GameMap::find_way(short * box_data, short x, short y){
current_map[x][y] = -1;//标记已经走过
if (current_map[x - 1][y] > 1 && current_map[x - 2][y] <= 0)
box_data[current_map[x - 1][y] - 2] |= 1 << 3;//up
if (!current_map[x - 1][y])
find_way(box_data, x - 1, y);
if (current_map[x + 1][y] > 1 && current_map[x + 2][y] <= 0)
box_data[current_map[x + 1][y] - 2] |= 1 << 2;//down
if (!current_map[x + 1][y])
find_way(box_data, x + 1, y);
if (current_map[x][y - 1] > 1 && current_map[x][y - 2] <= 0)
box_data[current_map[x][y - 1] - 2] |= 1 << 1;//left
if (!current_map[x][y - 1])
find_way(box_data, x, y - 1);
if (current_map[x][y + 1] > 1 && current_map[x][y + 2] <= 0)
box_data[current_map[x][y + 1] - 2] |= 1;//right
if (!current_map[x][y + 1])
find_way(box_data, x, y + 1);
}
void GameMap::do_translate()
{
Map_uper = Map_left = MAX_LEN;
short Map_bottom = 0, Map_rightside = 0;
for (int i = 1; i <= Map_length; ++i)
for (int j = 1; j <= Map_width; ++j) {
if (!Game_Wall[i][j]) {
if (i < Map_uper) Map_uper = i;
if (i > Map_bottom) Map_bottom = i;
if (j < Map_left) Map_left = j;
if (j > Map_rightside) Map_rightside = j;
}
}
Map_width = Map_rightside - Map_left + 1;
Map_length = Map_bottom - Map_uper + 1;
short delta_x, delta_y, Map_center_x, Map_center_y;
Map_center_x = (Map_uper + Map_bottom + 1) / 2;
Map_center_y = (Map_left + Map_rightside + 1) / 2;
delta_x = Window_center_x - Map_center_x;
delta_y = Window_center_y - Map_center_y;
memset(Game_Mark, false, sizeof(Game_Mark));
for (int i = Map_uper; i <= Map_bottom; ++i)
for (int j = Map_left; j <= Map_rightside; ++j)
Game_Mark[i + delta_x][j + delta_y] = Game_box[i][j];
for (int i = 0; i < MAX_LEN; ++i)
for (int j = 0; j < MAX_LEN; ++j)
Game_box[i][j] = Game_Mark[i][j];
memset(Game_Mark, false, sizeof(Game_Mark));
for (int i = Map_uper; i <= Map_bottom; ++i)
for (int j = Map_left; j <= Map_rightside; ++j)
Game_Mark[i + delta_x][j + delta_y] = Game_Goal[i][j];
for (int i = 0; i < MAX_LEN; ++i)
for (int j = 0; j < MAX_LEN; ++j)
Game_Goal[i][j] = Game_Mark[i][j];
memset(Game_Mark, 1, sizeof(Game_Mark));
for (int i = Map_uper; i <= Map_bottom; ++i)
for (int j = Map_left; j <= Map_rightside; ++j)
Game_Mark[i + delta_x][j + delta_y] = Game_Wall[i][j];
for (int i = 0; i < MAX_LEN; ++i)
for (int j = 0; j < MAX_LEN; ++j)
Game_Wall[i][j] = Game_Mark[i][j];
player_x += delta_x;
player_y += delta_y;
Map_uper += delta_x;
Map_bottom += delta_x;
Map_left += delta_y;
Map_rightside += delta_y;
memset(Game_Mark, 0, sizeof(Game_Mark));
for (int i = Map_uper; i <= Map_bottom; ++i)
for (int j = Map_left; j <= Map_rightside; ++j) {
if (Game_Wall[i][j]) continue;
for (int k = i - 1; k <= i + 1; ++k)
for (int l = j - 1; l <= j + 1; ++l)
if (Game_Wall[k][l])
Game_Mark[k][l] = true;
}
}
void GameMap::get(std::istream& ist)
{
short line{ 1 };
short column{ 0 };
std::vector<short> column_in_line;
char ch{ ' ' };
while (!ist.eof()) {
ch = ist.get();
int n = int(ch);
if (n == 13) {
continue;
}
else {
if (ist.eof()) {
++line;
break;
}
else {
switch (ch) {
case ' ':
break;
case nothing:
{++column;
Game_Wall[line][column] = false;
break; }
case player:
{++column;
++player_num;
player_x = line;
player_y = column;
Game_Wall[line][column] = false;
break; }
case box:
{++column;
++boxes_num;
Game_Wall[line][column] = false;
Game_box[line][column] = true;
break; }
case goal_box:
{++column;
++boxes_num;
++Goals_num;
Game_Wall[line][column] = false;
Game_box[line][column] = true;
Game_Goal[line][column] = true;
break; }
case player_goal:
{++column;
++player_num;
player_x = line;
player_y = column;
++Goals_num;
Game_Wall[line][column] = false;
Game_Goal[line][column] = true;
Game_Goal[line][column] = true;
break; }
case goal:
{++column;
++Goals_num;
Game_Wall[line][column] = false;
Game_Goal[line][column] = true;
break; }
case wall:
{++column;
Game_Wall[line][column] = true;
break; }
case '\n':
{
if (column != 0)
{
column_in_line.push_back(column); // column_in_line[0]=第一行的方块数;之后类同。
column = 0;
++line;
}
break;
}
default:
throw std::runtime_error{ "You tricky child put some illegal characters in the *.bgdat file?!" };
break;
}
}
}
}
if (line > 1&&column_in_line.size()>0)
{
for (int i = 0; i < column_in_line.size() - 1; ++i)
{
if (column_in_line[i] != column_in_line[i + 1])
throw std::runtime_error{ "You should have the same column in each line!" };
}
}
if (player_num > 1) {
throw std::runtime_error{ "More than one Player in a map!" };
}
if(column_in_line.size()>0)
Map_width = column_in_line[0];
Map_length = line - 1;
if (Map_width > 13 || Map_length > 13) {
throw std::runtime_error{ "The map is bigger than 13*13!" };
}
}
void GameMap::init() {
Goals_num = 0;
boxes_num = 0;
player_num = 0;
Map_length = 0;
Map_width = 0;
player_x = -MAX_LEN;
player_y = -MAX_LEN;
memset(Game_Wall, 1, sizeof(Game_Wall));
memset(Game_box, 0, sizeof(Game_box));
memset(Game_Goal, 0, sizeof(Game_Goal));
}
void GameMap::judge() {
if (player_num < 1)throw std::runtime_error{ "NO Player!" };
if (boxes_num != Goals_num)throw std::runtime_error{ "Boxes don't match with goals." };
if (boxes_num == 0)throw std::runtime_error{ "Trivial!" };
return;
}
|
6b30c5076c7fd7b8a3c3235bbaad25a2e696531a | 8b4a9e04e65c9ef7283b4e33421817c49c5b3173 | /head/src/nau/geometry/poseOffset.cpp | d4861592924a0bbc4793d4a038c0d90fd45c92a9 | [
"MIT"
] | permissive | david-leal/nau | 365f0bff16349345039a74de544d12433d74c23a | 57a55567e35ce6b095d15e4aed064160a79aacb1 | refs/heads/master | 2020-12-02T19:48:06.654597 | 2016-09-19T21:41:13 | 2016-09-19T21:41:13 | 46,269,171 | 0 | 0 | null | 2015-11-16T10:57:46 | 2015-11-16T10:57:46 | null | UTF-8 | C++ | false | false | 434 | cpp | poseOffset.cpp | #include "nau/geometry/poseOffset.h"
using namespace nau::geometry;
PoseOffset::PoseOffset(unsigned int aSize) :
m_vOffset(aSize),
m_Size(aSize)
{}
PoseOffset::~PoseOffset()
{
}
void
PoseOffset::addPoseOffset(int index, float x, float y, float z)
{
if (index >= m_Size)
return;
else
m_vOffset.at(index).set(x, y, z);
}
std::vector<vec3>
PoseOffset::getOffsets()
{
return m_vOffset;
}
|
147cf180c4dc4c4abb5e6385f99869983e1b5a7b | adc4d04471e3fced971ae7abca7663b2a3885150 | /frameworks/runtime-src/Classes/GameNetMgr/ToolBASE64.h | 8745c3e9d06f6b03adf0f234db4e42d51244c1c1 | [] | no_license | s752167062/MJPlatform | 0aa81b38225b64852d89d5a42a6b6e6d6081016b | cacabedcf0de923740c81cbe12464774334a2cd3 | refs/heads/master | 2020-03-21T06:50:59.573272 | 2019-01-22T08:24:34 | 2019-01-22T08:24:34 | 138,245,383 | 1 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 438 | h | ToolBASE64.h | /*
@网络通信加解密
@author sunfan
@date 2017/05/05
*/
#ifndef ToolBASE64_h
#define ToolBASE64_h
#include <stdio.h>
#include <string>
class ToolBASE64{
public:
/* Base64 编码 */
static std::string base64_encode(const char* data, int data_len);
/* Base64 解码 */
static std::string base64_decode(const char* data, int data_len);
private:
static char find_pos(char ch);
};
#endif /* BASE64_hpp */
|
6f6ec134c5907118a4d7c7259261b752aa4c1ea7 | 877e2b7d601255053a394f77d9ece8c5641662ac | /leetcode107/btree_level_traversal2.cpp | ba51922526721472f8aed329aeb8461aebb31fb6 | [] | no_license | hyfeng/leetcode | 4947ec9cd56bccf11541e38ee21c2ed418046d14 | 8d5a5e1fcb48888d552e3ed3121e64dcdf257359 | refs/heads/master | 2020-03-29T18:07:37.455074 | 2019-10-10T08:51:03 | 2019-10-10T08:51:03 | 33,539,925 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,275 | cpp | btree_level_traversal2.cpp | /*
Given a binary tree, return the bottom-up level order traversal of its nodes' values. (ie, from left to right, level by level from leaf to root).
For example:
Given binary tree {3,9,20,#,#,15,7},
3
/ \
9 20
/ \
15 7
return its bottom-up level order traversal as:
[
[15,7],
[9,20],
[3]
]
*/
//Definition for binary tree
#include <iostream>
#include <cstring>
#include <vector>
#include <queue>
using namespace std;
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
class Solution {
public:
vector<vector<int> > levelOrderBottom(TreeNode *root) {
vector<vector<int> > layer;
queue<TreeNode*> q;
int num = 0;
if(root==NULL)return layer;
q.push(root);
++num;
traverse(layer,q,num);
return layer;
}
private:
void traverse(vector<vector<int> >&layer,queue<TreeNode*> &qu,int num){
int childs = 0;
vector<int> level;
while(num-->0){
TreeNode* p = qu.front();
level.push_back(p->val);
qu.pop();
if(p->left){
qu.push(p->left);
++childs;
}
if(p->right){
qu.push(p->right);
++childs;
}
}
if(childs>0)traverse(layer,qu,childs);
layer.push_back(level);
}
};
TreeNode* createTree(char *seri){
int len = strlen(seri);
if(len<3)return NULL;
TreeNode* root = new TreeNode(seri[1]-'0');
if(len==3)return root;
queue<TreeNode*> qu;
qu.push(root);
for(int i=3;i<len-1;i+=2){
TreeNode * p = qu.front();
qu.pop();
if(seri[i]!='#'){//left
TreeNode *q = new TreeNode(seri[i]-'0');
p->left=q;
qu.push(q);
}
i+=2;
if(seri[i]!='#'){
TreeNode *q = new TreeNode(seri[i]-'0');
p->right=q;
qu.push(q);
}
}
return root;
}
void preTrans(TreeNode *root){
if(root==NULL)return;
cout<<root->val<<',';
if(root->left!=NULL){
preTrans(root->left);
}
else{
cout<<"#"<<',';
}
if(root->right!=NULL){
preTrans(root->right);
}
else{
cout<<"#"<<',';
}
}
int main(){
TreeNode * root = createTree("{3,9,2,#,#,5,7}");
preTrans(root);cout<<endl;
Solution S;
vector<vector<int> > la = S.levelOrderBottom(root);
for(int i=0;i<la.size();++i){
vector<int>& q = la[i];
for(int j=0;j<q.size();++j)
cout<<q[j]<<' ';
cout<<endl;
}
system("pause");
return 0;
} |
2866e44d45855917298ae9c8486754384567abf9 | e393fad837587692fa7dba237856120afbfbe7e8 | /prac/first/ABC_057_C-Digits_in_Multiplication.cpp | d1f19f2082d3a87cb6e887379e3046f242043c81 | [] | no_license | XapiMa/procon | 83e36c93dc55f4270673ac459f8c59bacb8c6924 | e679cd5d3c325496490681c9126b8b6b546e0f27 | refs/heads/master | 2020-05-03T20:18:47.783312 | 2019-05-31T12:33:33 | 2019-05-31T12:33:33 | 178,800,254 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 420 | cpp | ABC_057_C-Digits_in_Multiplication.cpp | typedef long long ll;
#define rep(i,N) for (ll i = 1; i < N; i++)
#include <iostream>
#include <algorithm>
#include <cmath>
using namespace std;
int main(){
ll N;
ll res = 10000000000;
cin >> N;
for (ll i = 1; i <= sqrt(N); i++) {
if(N%i!=0) continue;
res = min(res,max(i,N/i));
}
cout << (int)log10(res)+1 << endl;
return 0;
}
|
c685653093ddba4e2f055d7d85c67afa3c4ed7f9 | f3c9dc56bfc9bdb899b09a6645da68788cacc521 | /include/BaselineSequentialVertexPartitioning.h | dd2e998a7a27b8f517f0bb7752d21a2644a6264d | [] | no_license | cfmusoles/hyperPraw | 4cc21b60d1cafab6efbfac47891c15e64b3a8614 | b041a45fd0020c2baeb1bc8f5a37d6a5c3577d3a | refs/heads/master | 2023-05-08T14:19:13.986590 | 2021-01-07T14:05:15 | 2021-01-07T14:05:15 | 155,267,845 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,578 | h | BaselineSequentialVertexPartitioning.h | #ifndef BASELINE_SEQUENTIAL_VERTEX_PARTITION_PARTITIONING
#define BASELINE_SEQUENTIAL_VERTEX_PARTITION_PARTITIONING
#include <vector>
#include <algorithm>
#include <set>
#include <cstring>
#include <cstdio>
#include <stdlib.h>
#include <string>
#include "Partitioning.h"
#include "PRAW.h"
class BaselineSequentialVertexPartitioning : public Partitioning {
public:
BaselineSequentialVertexPartitioning(char* experimentName, char* graph_file, float imbalance_tolerance) : Partitioning(graph_file,imbalance_tolerance) {
experiment_name = experimentName;
}
virtual ~BaselineSequentialVertexPartitioning() {}
virtual void perform_partitioning(int num_processes,int process_id, int* iterations) {
// Uses Alistairh's basic hypergraph partitioning to assign vertices to processes
if(num_processes <= 1) {
PRINTF("Partitioning not required\n");
return;
}
// initialise vertex weight values
int* vtx_wgt = (int*)calloc(num_vertices,sizeof(int));
for(int ii =0; ii < num_vertices; ii++) {
vtx_wgt[ii] = 1;
}
if(process_id == 0) {
*iterations = PRAW::BaselineSequentialVertexPartitioning(experiment_name,partitioning, num_processes, hgraph_name, vtx_wgt, imbalance_tolerance);
}
MPI_Barrier(MPI_COMM_WORLD);
// share new partitioning with other processes
MPI_Bcast(partitioning,num_vertices,MPI_LONG,0,MPI_COMM_WORLD);
// clean up operations
free(vtx_wgt);
}
private:
char* experiment_name = NULL;
};
#endif
|
71da8d008744553fa1d9d2f226e7c3c5722e40fb | d0ea0fe8ce8464364d0ea2b7f2b58e92a049689f | /tests/test_exe/src/cases/test_auto_deallocate.cpp | d817ce4178abb9888a67f125bed518651538d536 | [
"MIT"
] | permissive | DimaBond174/FastMemPool | 0ff963139177d26fd6101d65a7ce9ca5f5c9e993 | f73496d973cc7a6fd4518bdd5b2a55b700d7116b | refs/heads/master | 2022-12-04T05:11:48.199607 | 2020-08-13T04:50:26 | 2020-08-13T04:50:26 | 280,652,536 | 15 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 390 | cpp | test_auto_deallocate.cpp | #include "fast_mem_pool.h"
/**
* @brief test_auto_deallocate
* @return
* Testing automatic memory return for OS malloc
*/
bool test_auto_deallocate()
{
FastMemPool<100, 10, 10> memPool;
void *ptr = nullptr;
for (int i = 0; i < 100; ++i) {
void *ptr = memPool.fmalloc(101);
}
if (ptr)
{
memPool.ffree(ptr);
}
// check mem leak of the process
return true;
}
|
230e08a1fc4ab22355b05706cc02bd74326036b6 | 9e814458bb22a2ed0cab1fb046928ad165e50468 | /src/core/hw/gfxip/gfx9/gfx9CmdUtil.h | ddc54c2acd9ff70298d4410c9f794f3b0a02b0b3 | [
"LicenseRef-scancode-unknown-license-reference",
"MIT",
"Apache-2.0"
] | permissive | DadSchoorse/pal | b54785b53983691df55a1a3eecdc4375efe50931 | 02ac99ba650afb3aebff3eb8006862ce93d31968 | refs/heads/master | 2023-06-03T07:38:00.248167 | 2021-06-10T08:14:52 | 2021-06-10T08:15:50 | 378,459,817 | 1 | 0 | MIT | 2021-06-19T16:43:58 | 2021-06-19T16:43:57 | null | UTF-8 | C++ | false | false | 34,925 | h | gfx9CmdUtil.h | /*
***********************************************************************************************************************
*
* Copyright (c) 2015-2021 Advanced Micro Devices, Inc. All Rights Reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
**********************************************************************************************************************/
#pragma once
#include "core/hw/gfxip/gfx9/gfx9Chip.h"
#include "palDevice.h"
namespace Pal
{
class CmdStream;
class PipelineUploader;
enum class IndexType : uint32;
namespace Gfx9
{
class Device;
// The ACQUIRE_MEM and RELEASE_MEM packets can issue one "TC cache op" in addition to their other operations. This
// behavior is controlled by CP_COHER_CNTL but only certain bit combinations are legal. To be clear what the HW can do
// and avoid illegal combinations we abstract those bit combinations using this enum.
enum class TcCacheOp : uint32
{
Nop = 0, // Do nothing.
WbInvL1L2, // Flush and invalidate all TCP and TCC data.
WbInvL2Nc, // Flush and invalidate all TCC data that used the non-coherent MTYPE.
WbL2Nc, // Flush all TCC data that used the non-coherent MTYPE.
WbL2Wc, // Flush all TCC data that used the write-combined MTYPE.
InvL2Nc, // Invalidate all TCC data that used the non-coherent MTYPE.
InvL2Md, // Invalidate the TCC's read-only metadata cache.
InvL1, // Invalidate all TCP data.
InvL1Vol, // Invalidate all volatile TCP data.
Count
};
// GCR_CNTL bit fields for ACQUIRE_MEM and RELEASE_MEM are slightly different.
union Gfx10AcquireMemGcrCntl
{
struct
{
uint32 gliInv : 2;
uint32 gl1Range : 2;
uint32 glmWb : 1;
uint32 glmInv : 1;
uint32 glkWb : 1;
uint32 glkInv : 1;
uint32 glvInv : 1;
uint32 gl1Inv : 1;
uint32 gl2Us : 1;
uint32 gl2Range : 2;
uint32 gl2Discard : 1;
uint32 gl2Inv : 1;
uint32 gl2Wb : 1;
uint32 seq : 2;
uint32 : 14;
} bits;
uint32 u32All;
};
union Gfx10ReleaseMemGcrCntl
{
struct
{
uint32 glmWb : 1;
uint32 glmInv : 1;
uint32 glvInv : 1;
uint32 gl1Inv : 1;
uint32 gl2Us : 1;
uint32 gl2Range : 2;
uint32 gl2Discard : 1;
uint32 gl2Inv : 1;
uint32 gl2Wb : 1;
uint32 seq : 2;
uint32 reserved1 : 1;
uint32 : 18;
uint32 reserved2 : 1;
} bits;
uint32 u32All;
};
// This table was taken from the ACQUIRE_MEM packet spec.
static constexpr uint32 Gfx9TcCacheOpConversionTable[] =
{
0, // Nop
Gfx09_10::CP_COHER_CNTL__TC_WB_ACTION_ENA_MASK | Gfx09_10::CP_COHER_CNTL__TC_ACTION_ENA_MASK, // WbInvL1L2
Gfx09_10::CP_COHER_CNTL__TC_WB_ACTION_ENA_MASK | Gfx09_10::CP_COHER_CNTL__TC_ACTION_ENA_MASK
| Gfx09_10::CP_COHER_CNTL__TC_NC_ACTION_ENA_MASK, // WbInvL2Nc
Gfx09_10::CP_COHER_CNTL__TC_WB_ACTION_ENA_MASK | Gfx09_10::CP_COHER_CNTL__TC_NC_ACTION_ENA_MASK, // WbL2Nc
Gfx09_10::CP_COHER_CNTL__TC_WB_ACTION_ENA_MASK | Gfx09_10::CP_COHER_CNTL__TC_WC_ACTION_ENA_MASK, // WbL2Wc
Gfx09_10::CP_COHER_CNTL__TC_ACTION_ENA_MASK | Gfx09_10::CP_COHER_CNTL__TC_NC_ACTION_ENA_MASK, // InvL2Nc
Gfx09_10::CP_COHER_CNTL__TC_ACTION_ENA_MASK | Gfx09_10::CP_COHER_CNTL__TC_INV_METADATA_ACTION_ENA_MASK, // InvL2Md
Gfx09_10::CP_COHER_CNTL__TCL1_ACTION_ENA_MASK, // InvL1
Gfx09_10::CP_COHER_CNTL__TCL1_ACTION_ENA_MASK | Gfx09_10::CP_COHER_CNTL__TCL1_VOL_ACTION_ENA_MASK, // InvL1Vol
};
// In addition to the a TC cache op, ACQUIRE_MEM can flush or invalidate additional caches independently. It is easiest
// to capture all of this information if we use an input structure for BuildAcquireMem.
struct AcquireMemInfo
{
union
{
struct
{
uint32 usePfp : 1; // If true the PFP will process this packet. Only valid on the universal engine.
uint32 invSqI$ : 1; // Invalidate the SQ instruction caches.
uint32 invSqK$ : 1; // Invalidate the SQ scalar caches.
uint32 flushSqK$ : 1; // Flush the SQ scalar caches.
uint32 wbInvCbData : 1; // Flush and invalidate the CB data cache. Only valid on the universal engine.
uint32 wbInvDb : 1; // Flush and invalidate the DB data and metadata caches. Only valid on universal.
uint32 reserved : 26;
};
uint32 u32All;
} flags;
EngineType engineType;
regCP_ME_COHER_CNTL cpMeCoherCntl; // All "dest base" bits to wait on. Only valid on the universal engine.
TcCacheOp tcCacheOp; // An optional, additional cache operation to issue.
// These define the address range being acquired. Use FullSyncBaseAddr and FullSyncSize for a global acquire.
gpusize baseAddress;
gpusize sizeBytes;
};
// Explicit version of AcquireMemInfo struct.
struct ExplicitAcquireMemInfo
{
union
{
struct
{
uint32 usePfp : 1; // If true the PFP will process this packet. Only valid on the universal engine.
uint32 reservedFutureHw : 1; // Placeholder
uint32 reserved : 30;
};
uint32 u32All;
} flags;
EngineType engineType;
uint32 coherCntl;
uint32 gcrCntl;
// These define the address range being acquired. Use FullSyncBaseAddr and FullSyncSize for a global acquire.
gpusize baseAddress;
gpusize sizeBytes;
};
// To easily see the the differences between ReleaseMem and AcquireMem, we want to use an input structure
// for BuildAcquireMem.
struct ReleaseMemInfo
{
EngineType engineType;
VGT_EVENT_TYPE vgtEvent;
TcCacheOp tcCacheOp; // The cache operation to issue.
gpusize dstAddr;
uint32 dataSel; // One of the data_sel_*_release_mem enumerations
uint64 data; // data to write, ignored except for DATA_SEL_SEND_DATA{32,64}
};
// Explicit version of ReleaseMemInfo struct.
struct ExplicitReleaseMemInfo
{
EngineType engineType;
VGT_EVENT_TYPE vgtEvent;
uint32 coherCntl;
uint32 gcrCntl;
gpusize dstAddr;
uint32 dataSel; // One of the data_sel_*_release_mem enumerations
uint64 data; // data to write, ignored except for DATA_SEL_SEND_DATA{32,64}
};
// The "official" "event-write" packet definition (see: PM4_MEC_EVENT_WRITE) contains "extra" dwords that aren't
// necessary (and would cause problems if they existed) for event writes other than "". Define a "plain" event-write
// packet definition here.
struct PM4_ME_NON_SAMPLE_EVENT_WRITE
{
PM4_ME_TYPE_3_HEADER header;
uint32 ordinal2;
};
// Data required to perform a DMA Data transfer (aka CPDMA).
//
// Note that the "sync" flag should be set in almost all cases. The two exceptions are:
// 1. The caller will manually synchronize the CP DMA engine using another DMA.
// 2. The caller is operating under "CoherCopy/HwPipePostBlt" semantics and a CmdBarrier call will be issued. This
// case is commonly referred to as a "CP Blt".
//
// In case #2, the caller must update the GfxCmdBufferState by calling the relevant SetGfxCmdBuf* functions.
// Furthermore, the caller must not set "disWc" because write-confirms are necessary for the barrier to guarantee
// that the CP DMA writes have made it to their destination (memory, L2, etc.).
struct DmaDataInfo
{
PFP_DMA_DATA_dst_sel_enum dstSel;
gpusize dstAddr; // Destination address for dstSel Addr or offset for GDS
PFP_DMA_DATA_das_enum dstAddrSpace; // Destination address space
PFP_DMA_DATA_src_sel_enum srcSel;
uint32 srcData; // Source data for srcSel data or offset for srcSel GDS
gpusize srcAddr; // Source gpu virtual address
PFP_DMA_DATA_sas_enum srcAddrSpace; // Source address space
uint32 numBytes; // Number of bytes to copy
bool usePfp; // true chooses PFP engine, false chooses ME
bool sync; // if true, all command processing on the selected engine
// (see: usePfp) is halted until this packet is finished
bool disWc; // set to disable write-confirm
bool rawWait; // Read-after-write, forces the CP to wait for all previous DMA ops
// to finish before starting this one.
Pm4Predicate predicate; // Set if currently using predication
};
// Data required to build a write_data packet. We try to set up this struct so that zero-initializing gives reasonable
// values for rarely changed members like predicate, dontWriteConfirm, etc.
struct WriteDataInfo
{
EngineType engineType; // Which PAL engine will this packet be executed on?
gpusize dstAddr; // Destination GPU memory address or memory mapped register offset.
uint32 engineSel; // Which CP engine executes this packet (see XXX_WRITE_DATA_engine_sel_enum)
// Ignored on the MEC.
uint32 dstSel; // Where to write the data (see XXX_WRITE_DATA_dst_sel_enum)
Pm4Predicate predicate; // If this packet respects predication (zero defaults to disabled).
bool dontWriteConfirm; // If the engine should continue immediately without waiting for a write-confirm.
bool dontIncrementAddr; // If the engine should write every DWORD to the same destination address.
// Some memory mapped registers use this to stream in an array of data.
};
// On different hardware families, some registers have different register offsets. This structure stores the register
// offsets for some of these registers.
struct RegisterInfo
{
uint16 mmRlcPerfmonClkCntl;
uint16 mmRlcSpmGlobalMuxselAddr;
uint16 mmRlcSpmGlobalMuxselData;
uint16 mmRlcSpmSeMuxselAddr;
uint16 mmRlcSpmSeMuxselData;
uint16 mmEaPerfResultCntl;
uint16 mmAtcPerfResultCntl;
uint16 mmAtcL2PerfResultCntl;
uint16 mmMcVmL2PerfResultCntl;
uint16 mmRpbPerfResultCntl;
uint16 mmSpiShaderPgmLoLs;
uint16 mmSpiShaderPgmLoEs;
uint16 mmVgtGsMaxPrimsPerSubGroup;
uint16 mmDbDfsmControl;
uint16 mmUserDataStartHsShaderStage;
uint16 mmUserDataStartGsShaderStage;
uint16 mmPaStereoCntl;
uint16 mmPaStateStereoX;
uint16 mmComputeShaderChksum;
};
// Pre-baked commands to prefetch (prime caches) for a pipeline. This can either be done with a PRIME_UTCL2 packet,
// which will prime the UTCL2 (L2 TLB) or with a DMA_DATA packet, which will also prime GL2.
struct PipelinePrefetchPm4
{
union
{
PM4_PFP_DMA_DATA dmaData;
PM4_PFP_PRIME_UTCL2 primeUtcl2;
};
uint32 spaceNeeded;
};
// =====================================================================================================================
// Utility class which provides routines to help build PM4 packets.
class CmdUtil
{
public:
explicit CmdUtil(const Device& device);
~CmdUtil() {}
// Returns the number of DWORDs that are required to chain two chunks
static uint32 ChainSizeInDwords(EngineType engineType);
static constexpr uint32 CondIndirectBufferSize = PM4_PFP_COND_INDIRECT_BUFFER_SIZEDW__CORE;
static constexpr uint32 DispatchDirectSize = PM4_PFP_DISPATCH_DIRECT_SIZEDW__CORE;
static constexpr uint32 DispatchIndirectMecSize = PM4_MEC_DISPATCH_INDIRECT_SIZEDW__CORE;
static constexpr uint32 DrawIndexAutoSize = PM4_PFP_DRAW_INDEX_AUTO_SIZEDW__CORE;
static constexpr uint32 DrawIndex2Size = PM4_PFP_DRAW_INDEX_2_SIZEDW__CORE;
static constexpr uint32 DrawIndexOffset2Size = PM4_PFP_DRAW_INDEX_OFFSET_2_SIZEDW__CORE;
static constexpr uint32 DispatchTaskMeshGfxSize = PM4_ME_DISPATCH_TASKMESH_GFX_SIZEDW__GFX10COREPLUS;
static constexpr uint32 DispatchTaskMeshDirectMecSize =
PM4_MEC_DISPATCH_TASKMESH_DIRECT_ACE_SIZEDW__GFX10COREPLUS;
static constexpr uint32 DispatchTaskMeshIndirectMecSize =
PM4_MEC_DISPATCH_TASKMESH_INDIRECT_MULTI_ACE_SIZEDW__GFX10COREPLUS;
static constexpr uint32 MinNopSizeInDwords = 1; // all gfx9 HW supports 1-DW NOP packets
static_assert (PM4_PFP_COND_EXEC_SIZEDW__CORE == PM4_MEC_COND_EXEC_SIZEDW__CORE,
"Conditional execution packet size does not match between PFP and compute engines!");
static_assert (PM4_PFP_COND_EXEC_SIZEDW__CORE == PM4_CE_COND_EXEC_SIZEDW__HASCE,
"Conditional execution packet size does not match between PFP and constant engines!");
static constexpr uint32 CondExecSizeDwords = PM4_PFP_COND_EXEC_SIZEDW__CORE;
static constexpr uint32 ContextRegRmwSizeDwords = PM4_ME_CONTEXT_REG_RMW_SIZEDW__CORE;
static constexpr uint32 RegRmwSizeDwords = PM4_ME_REG_RMW_SIZEDW__CORE;
static constexpr uint32 ConfigRegSizeDwords = PM4_PFP_SET_UCONFIG_REG_SIZEDW__CORE;
static constexpr uint32 ContextRegSizeDwords = PM4_PFP_SET_CONTEXT_REG_SIZEDW__CORE;
static constexpr uint32 DmaDataSizeDwords = PM4_PFP_DMA_DATA_SIZEDW__CORE;
static constexpr uint32 NumInstancesDwords = PM4_PFP_NUM_INSTANCES_SIZEDW__CORE;
static constexpr uint32 OcclusionQuerySizeDwords = PM4_PFP_OCCLUSION_QUERY_SIZEDW__CORE;
static constexpr uint32 ShRegSizeDwords = PM4_ME_SET_SH_REG_SIZEDW__CORE;
static constexpr uint32 ShRegIndexSizeDwords = PM4_PFP_SET_SH_REG_INDEX_SIZEDW__CORE;
static constexpr uint32 WaitRegMemSizeDwords = PM4_ME_WAIT_REG_MEM_SIZEDW__CORE;
static constexpr uint32 WaitRegMem64SizeDwords = PM4_ME_WAIT_REG_MEM64_SIZEDW__CORE;
static constexpr uint32 WriteDataSizeDwords = PM4_ME_WRITE_DATA_SIZEDW__CORE;
static constexpr uint32 WriteNonSampleEventDwords = (sizeof(PM4_ME_NON_SAMPLE_EVENT_WRITE) / sizeof(uint32));
// The INDIRECT_BUFFER and COND_INDIRECT_BUFFER packet have a hard-coded IB size of 20 bits.
static constexpr uint32 MaxIndirectBufferSizeDwords = (1 << 20) - 1;
// The COPY_DATA src_reg_offset and dst_reg_offset fields have a bit-width of 18 bits.
static constexpr uint32 MaxCopyDataRegOffset = (1 << 18) - 1;
///@note GFX10 added the ability to do ranged checks when for Flush/INV ops to GL1/GL2 (so that you can just
/// Flush/INV necessary lines instead of the entire cache). Since these caches are physically tagged, this
/// can invoke a high penalty for large surfaces so limit the surface size allowed.
static constexpr uint64 Gfx10AcquireMemGl1Gl2RangedCheckMaxSurfaceSizeBytes = (64 * 1024);
static bool IsContextReg(uint32 regAddr);
static bool IsUserConfigReg(uint32 regAddr);
static bool IsShReg(uint32 regAddr);
static ME_WAIT_REG_MEM_function_enum WaitRegMemFunc(CompareFunc compareFunc);
// Checks if the register offset provided can be read or written using a COPY_DATA packet.
static bool CanUseCopyDataRegOffset(uint32 regOffset) { return (((~MaxCopyDataRegOffset) & regOffset) == 0); }
bool CanUseCsPartialFlush(EngineType engineType) const;
size_t BuildAcquireMem(
const AcquireMemInfo& acquireMemInfo,
void* pBuffer) const;
size_t ExplicitBuildAcquireMem(
const ExplicitAcquireMemInfo& acquireMemInfo,
void* pBuffer) const;
static size_t BuildAtomicMem(
AtomicOp atomicOp,
gpusize dstMemAddr,
uint64 srcData,
void* pBuffer);
static size_t BuildClearState(
PFP_CLEAR_STATE_cmd_enum command,
void* pBuffer);
static size_t BuildCondExec(
gpusize gpuVirtAddr,
uint32 sizeInDwords,
void* pBuffer);
static size_t BuildCondIndirectBuffer(
CompareFunc compareFunc,
gpusize compareGpuAddr,
uint64 data,
uint64 mask,
bool constantEngine,
void* pBuffer);
static size_t BuildContextControl(
const PM4_PFP_CONTEXT_CONTROL& contextControl,
void* pBuffer);
size_t BuildContextRegRmw(
uint32 regAddr,
uint32 regMask,
uint32 regData,
void* pBuffer) const;
size_t BuildRegRmw(
uint32 regAddr,
uint32 orMask,
uint32 andMask,
void* pBuffer) const;
static size_t BuildCopyDataGraphics(
uint32 engineSel,
ME_COPY_DATA_dst_sel_enum dstSel,
gpusize dstAddr,
ME_COPY_DATA_src_sel_enum srcSel,
gpusize srcAddr,
ME_COPY_DATA_count_sel_enum countSel,
ME_COPY_DATA_wr_confirm_enum wrConfirm,
void* pBuffer);
static size_t BuildCopyDataCompute(
MEC_COPY_DATA_dst_sel_enum dstSel,
gpusize dstAddr,
MEC_COPY_DATA_src_sel_enum srcSel,
gpusize srcAddr,
MEC_COPY_DATA_count_sel_enum countSel,
MEC_COPY_DATA_wr_confirm_enum wrConfirm,
void* pBuffer);
// This generic version of BuildCopyData works on graphics and compute but doesn't provide any user-friendly enums.
// The caller must make sure that the arguments they use are legal on their engine.
static size_t BuildCopyData(
EngineType engineType,
uint32 engineSel,
uint32 dstSel,
gpusize dstAddr,
uint32 srcSel,
gpusize srcAddr,
uint32 countSel,
uint32 wrConfirm,
void* pBuffer);
static size_t BuildPerfmonControl(
uint32 perfMonCtlId,
bool enable,
uint32 eventSelect,
uint32 eventUnitMask,
void* pBuffer);
template <bool dimInThreads, bool forceStartAt000>
size_t BuildDispatchDirect(
uint32 xDim,
uint32 yDim,
uint32 zDim,
Pm4Predicate predicate,
bool isWave32,
bool useTunneling,
bool disablePartialPreempt,
void* pBuffer) const;
static size_t BuildDispatchIndirectGfx(
gpusize byteOffset,
Pm4Predicate predicate,
bool isWave32,
void* pBuffer);
size_t BuildDispatchIndirectMec(
gpusize address,
bool isWave32,
bool useTunneling,
bool disablePartialPreempt,
void* pBuffer) const;
static size_t BuildDrawIndex2(
uint32 indexCount,
uint32 indexBufSize,
gpusize indexBufAddr,
Pm4Predicate predicate,
void* pBuffer);
static size_t BuildDrawIndexOffset2(
uint32 indexCount,
uint32 indexBufSize,
uint32 indexOffset,
Pm4Predicate predicate,
void* pBuffer);
size_t BuildDrawIndexIndirect(
gpusize offset,
uint32 baseVtxLoc,
uint32 startInstLoc,
Pm4Predicate predicate,
void* pBuffer) const;
size_t BuildDrawIndexIndirectMulti(
gpusize offset,
uint32 baseVtxLoc,
uint32 startInstLoc,
uint32 drawIndexLoc,
uint32 stride,
uint32 count,
gpusize countGpuAddr,
Pm4Predicate predicate,
void* pBuffer) const;
static size_t BuildDrawIndirectMulti(
gpusize offset,
uint32 baseVtxLoc,
uint32 startInstLoc,
uint32 drawIndexLoc,
uint32 stride,
uint32 count,
gpusize countGpuAddr,
Pm4Predicate predicate,
void* pBuffer);
static size_t BuildDrawIndexAuto(
uint32 indexCount,
bool useOpaque,
Pm4Predicate predicate,
void* pBuffer);
static size_t BuildTaskStateInit(
Pm4ShaderType shaderType,
gpusize controlBufferAddr,
Pm4Predicate predicate,
void* pBuffer);
template <bool IssueSqttMarkerEvent>
static size_t BuildDispatchTaskMeshGfx(
uint32 tgDimOffset,
uint32 ringEntryLoc,
Pm4Predicate predicate,
void* pBuffer);
static size_t BuildDispatchMeshIndirectMulti(
gpusize dataOffset,
uint32 xyzOffset,
uint32 drawIndexOffset,
uint32 count,
uint32 stride,
gpusize countGpuAddr,
Pm4Predicate predicate,
void* pBuffer);
static size_t BuildDispatchTaskMeshIndirectMultiAce(
gpusize dataOffset,
uint32 ringEntryLoc,
uint32 xyzDimLoc,
uint32 dispatchIndexLoc,
uint32 count,
uint32 stride,
gpusize countGpuAddr,
bool isWave32,
Pm4Predicate predicate,
void* pBuffer);
static size_t BuildDispatchTaskMeshDirectAce(
uint32 xDim,
uint32 yDim,
uint32 zDim,
uint32 ringEntryLoc,
Pm4Predicate predicate,
bool isWave32,
void* pBuffer);
static size_t BuildDmaData(
DmaDataInfo& dmaDataInfo,
void* pBuffer);
static size_t BuildDumpConstRam(
gpusize dstGpuAddr,
uint32 ramByteOffset,
uint32 dwordSize,
void* pBuffer);
static size_t BuildDumpConstRamOffset(
uint32 dstAddrOffset,
uint32 ramByteOffset,
uint32 dwordSize,
void* pBuffer);
static size_t BuildNonSampleEventWrite(
VGT_EVENT_TYPE vgtEvent,
EngineType engineType,
void* pBuffer);
size_t BuildSampleEventWrite(
VGT_EVENT_TYPE vgtEvent,
ME_EVENT_WRITE_event_index_enum eventIndex,
EngineType engineType,
gpusize gpuAddr,
void* pBuffer) const;
size_t BuildExecutionMarker(
gpusize markerAddr,
uint32 markerVal,
uint64 clientHandle,
uint32 markerType,
void* pBuffer) const;
static size_t BuildIncrementCeCounter(void* pBuffer);
static size_t BuildIncrementDeCounter(void* pBuffer);
static size_t BuildIndexAttributesIndirect(gpusize baseAddr, uint16 index, void* pBuffer);
static size_t BuildIndexBase(gpusize baseAddr, void* pBuffer);
static size_t BuildIndexBufferSize(uint32 indexCount, void* pBuffer);
size_t BuildIndexType(uint32 vgtDmaIndexType, void* pBuffer) const;
static size_t BuildIndirectBuffer(
EngineType engineType,
gpusize ibAddr,
uint32 ibSize,
bool chain,
bool constantEngine,
bool enablePreemption,
void* pBuffer);
static size_t BuildLoadConfigRegs(
gpusize gpuVirtAddr,
const RegisterRange* pRanges,
uint32 rangeCount,
void* pBuffer);
static size_t BuildLoadContextRegs(
gpusize gpuVirtAddr,
const RegisterRange* pRanges,
uint32 rangeCount,
void* pBuffer);
static size_t BuildLoadContextRegs(
gpusize gpuVirtAddr,
uint32 startRegAddr,
uint32 count,
void* pBuffer);
template <bool directAddress>
size_t BuildLoadContextRegsIndex(
gpusize gpuVirtAddrOrAddrOffset,
uint32 startRegAddr,
uint32 count,
void* pBuffer) const;
size_t BuildLoadContextRegsIndex(
gpusize gpuVirtAddr,
uint32 count,
void* pBuffer) const;
static size_t BuildLoadConstRam(
gpusize srcGpuAddr,
uint32 ramByteOffset,
uint32 dwordSize,
void* pBuffer);
static size_t BuildLoadShRegs(
gpusize gpuVirtAddr,
const RegisterRange* pRanges,
uint32 rangeCount,
Pm4ShaderType shaderType,
void* pBuffer);
static size_t BuildLoadShRegs(
gpusize gpuVirtAddr,
uint32 startRegAddr,
uint32 count,
Pm4ShaderType shaderType,
void* pBuffer);
size_t BuildLoadShRegsIndex(
gpusize gpuVirtAddr,
uint32 count,
Pm4ShaderType shaderType,
void* pBuffer) const;
static size_t BuildLoadUserConfigRegs(
gpusize gpuVirtAddr,
const RegisterRange* pRanges,
uint32 rangeCount,
void* pBuffer);
static size_t BuildNop(size_t numDwords, void* pBuffer);
size_t BuildNumInstances(uint32 instanceCount, void* pBuffer) const;
static size_t BuildOcclusionQuery(gpusize queryMemAddr, gpusize dstMemAddr, void* pBuffer);
static size_t BuildPfpSyncMe(void* pBuffer);
static size_t BuildPrimeUtcL2(
gpusize gpuAddr,
uint32 cachePerm,
uint32 primeMode,
uint32 engineSel,
size_t requestedPages,
void* pBuffer);
size_t BuildReleaseMem(
const ReleaseMemInfo& releaseMemInfo,
void* pBuffer,
uint32 gdsAddr = 0,
uint32 gdsSize = 0) const;
size_t ExplicitBuildReleaseMem(
const ExplicitReleaseMemInfo& releaseMemInfo,
void* pBuffer,
uint32 gdsAddr = 0,
uint32 gdsSize = 0) const;
size_t BuildRewind(
bool offloadEnable,
bool valid,
void* pBuffer) const;
static size_t BuildSetBase(
gpusize address,
PFP_SET_BASE_base_index_enum baseIndex,
Pm4ShaderType shaderType,
void* pBuffer);
static size_t BuildSetBaseCe(
gpusize address,
CE_SET_BASE_base_index_enum baseIndex,
Pm4ShaderType shaderType,
void* pBuffer);
template <bool resetFilterCam = false>
size_t BuildSetOneConfigReg(
uint32 regAddr,
void* pBuffer,
PFP_SET_UCONFIG_REG_INDEX_index_enum index = index__pfp_set_uconfig_reg_index__default) const;
size_t BuildSetOneContextReg(
uint32 regAddr,
void* pBuffer,
PFP_SET_CONTEXT_REG_INDEX_index_enum index = index__pfp_set_context_reg_index__default__GFX09) const;
size_t BuildSetOneShReg(
uint32 regAddr,
Pm4ShaderType shaderType,
void* pBuffer) const;
size_t BuildSetOneShRegIndex(
uint32 regAddr,
Pm4ShaderType shaderType,
PFP_SET_SH_REG_INDEX_index_enum index,
void* pBuffer) const;
template <bool resetFilterCam = false>
size_t BuildSetSeqConfigRegs(
uint32 startRegAddr,
uint32 endRegAddr,
void* pBuffer,
PFP_SET_UCONFIG_REG_INDEX_index_enum index = index__pfp_set_uconfig_reg_index__default) const;
size_t BuildSetSeqContextRegs(
uint32 startRegAddr,
uint32 endRegAddr,
void* pBuffer,
PFP_SET_CONTEXT_REG_INDEX_index_enum index = index__pfp_set_context_reg_index__default__GFX09) const;
size_t BuildSetSeqShRegs(
uint32 startRegAddr,
uint32 endRegAddr,
Pm4ShaderType shaderType,
void* pBuffer) const;
size_t BuildSetSeqShRegsIndex(
uint32 startRegAddr,
uint32 endRegAddr,
Pm4ShaderType shaderType,
PFP_SET_SH_REG_INDEX_index_enum index,
void* pBuffer) const;
static size_t BuildSetPredication(
gpusize gpuVirtAddr,
bool predicationBool,
bool occlusionHint,
PredicateType predType,
bool continuePredicate,
void* pBuffer);
static size_t BuildStrmoutBufferUpdate(
uint32 bufferId,
uint32 sourceSelect,
uint32 explicitOffset,
gpusize dstGpuVirtAddr,
gpusize srcGpuVirtAddr,
void* pBuffer);
size_t BuildWaitCsIdle(EngineType engineType, gpusize timestampGpuAddr, void* pBuffer) const;
static size_t BuildWaitDmaData(void* pBuffer);
static size_t BuildWaitOnCeCounter(bool invalidateKcache, void* pBuffer);
static size_t BuildWaitOnDeCounterDiff(uint32 counterDiff, void* pBuffer);
size_t BuildWaitOnReleaseMemEventTs(
EngineType engineType,
VGT_EVENT_TYPE vgtEvent,
TcCacheOp tcCacheOp,
gpusize gpuAddr,
void* pBuffer) const;
static size_t BuildWaitRegMem(
EngineType engineType,
uint32 memSpace,
uint32 function,
uint32 engine,
gpusize addr,
uint32 reference,
uint32 mask,
void* pBuffer,
uint32 operation = static_cast<uint32>(operation__me_wait_reg_mem__wait_reg_mem));
static size_t BuildWaitRegMem64(
EngineType engineType,
uint32 memSpace,
uint32 function,
uint32 engine,
gpusize addr,
uint64 reference,
uint64 mask,
void* pBuffer);
static size_t BuildWriteConstRam(
const void* pSrcData,
uint32 ramByteOffset,
uint32 dwordSize,
void* pBuffer);
static size_t BuildWriteData(
const WriteDataInfo& info,
uint32 data,
void* pBuffer);
static size_t BuildWriteData(
const WriteDataInfo& info,
size_t dwordsToWrite,
const uint32* pData,
void* pBuffer);
static size_t BuildWriteDataPeriodic(
const WriteDataInfo& info,
size_t dwordsPerPeriod,
size_t periodsToWrite,
const uint32* pPeriodData,
void* pBuffer);
static size_t BuildCommentString(const char* pComment, Pm4ShaderType type, void* pBuffer);
size_t BuildNopPayload(const void* pPayload, uint32 payloadSize, void* pBuffer) const;
void BuildPipelinePrefetchPm4(const PipelineUploader& uploader, PipelinePrefetchPm4* pOutput) const;
size_t BuildPrimeGpuCaches(
const PrimeGpuCacheRange& primeGpuCacheRange,
void* pBuffer) const;
// Returns the register information for registers which have differing addresses between hardware families.
const RegisterInfo& GetRegInfo() const { return m_registerInfo; }
private:
static size_t BuildWriteDataInternal(
const WriteDataInfo& info,
size_t dwordsToWrite,
void* pBuffer);
uint32 Gfx10CalcAcquireMemGcrCntl(const AcquireMemInfo& acquireMemInfo) const;
uint32 Gfx10CalcReleaseMemGcrCntl(const ReleaseMemInfo& releaseMemInfo) const;
#if PAL_ENABLE_PRINTS_ASSERTS
void CheckShadowedContextReg(uint32 regAddr) const;
void CheckShadowedContextRegs(uint32 startRegAddr, uint32 endRegAddr) const;
void CheckShadowedShReg(Pm4ShaderType shaderType, uint32 regAddr, bool shouldBeShadowed = true) const;
void CheckShadowedShRegs(Pm4ShaderType shaderType, uint32 startRegAddr,
uint32 endRegAddr, bool shouldBeShadowed = true) const;
void CheckShadowedUserConfigRegs(uint32 startRegAddr, uint32 endRegAddr) const;
#endif
const Device& m_device;
const GfxIpLevel m_gfxIpLevel;
const uint32 m_cpUcodeVersion;
RegisterInfo m_registerInfo; // Addresses for registers whose addresses vary between hardware families.
#if PAL_ENABLE_PRINTS_ASSERTS
// If this is set, PAL will verify that all register writes fall within the ranges which get shadowed to GPU
// memory when mid command buffer preemption is enabled.
const bool m_verifyShadowedRegisters;
#endif
PAL_DISALLOW_DEFAULT_CTOR(CmdUtil);
PAL_DISALLOW_COPY_AND_ASSIGN(CmdUtil);
};
} // Gfx9
} // Pal
|
a61ea9605f1fd6c07a7aba07afbd82da4e1ad8ac | 0145f57c64284a17e33c36033fbc8ab913869159 | /hw51-60/hw52.cpp | 1f6b78c9ab93038b610b22d98a06f52cd60906fd | [] | no_license | Jeonyujeong/C-programing | 01bef274bb86da2e8c9b5356f35318d16a8adc1b | 2eeb8c82f7ac5f5fb96ca98e4b1b9ae447e6cdea | refs/heads/master | 2020-12-02T16:13:02.174250 | 2020-08-15T06:58:04 | 2020-08-15T06:58:04 | 96,519,522 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 658 | cpp | hw52.cpp | #include<stdio.h>
void swap(int*, int);
int main(void){
int a[] = {1, 2, 3, 4, 5, 6, 7, 8, 9};
int i, len;
len = sizeof(a)/4;
// printf("%lu\n", sizeof(a)/4);
printf("처음 배열에 저장된 값 : ");
for(i=0; i<len; i++)
printf("%d ", a[i]);
printf("\n");
swap(a, len);
printf("바뀐 배열에 저장된 값 :");
for(i=0; i<len; i++)
printf("%d ", a[i]);
printf("\n");
return 0;
}
void swap(int* arr, int len){
int temp, i;
// long unsigned int len;
// printf("%lu\n", sizeof(arr)/4);
// len = sizeof(arr)/4;
// printf("%lu\n", len);
for(i=0; i<len/2; i++){
temp = arr[i];
arr[i] = arr[len-i-1];
arr[len-i-1] = temp;
}
}
|
b174ca40cfa8f0801b6d7a62e11645726e95dc9a | d4dd2304c602bf2f8572e0f30f09d467fba33339 | /learn/cstandard.cpp | 36fb9e584881d528fec574ec36d697c366709d92 | [] | no_license | Doreamonsky/cpplearning | 10a0a0653a0aac10ab39c2c362d1ec8e5cef08de | 53f5aa19ef28f116b99f89c7eeffaac9a1645d81 | refs/heads/master | 2020-04-27T00:42:17.668652 | 2019-05-25T07:55:52 | 2019-05-25T07:55:52 | 173,942,818 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 340 | cpp | cstandard.cpp | #include <string.h>
#include <iostream>
using namespace std;
int main()
{
char character[100] = "Hello My Dearling Cpp";
char *charPtr = character + 6;
for (size_t i = 0; i < strlen(charPtr); i++)
{
cout << charPtr[i]; //Start from My Dearling Cpp
}
auto p = memchr(character, 'C', strlen(character));
} |
b1c2d77e7cda0381420a74f0f982602de2955317 | 3f3d5fd1bf296d0bf0e01200fbb876c61197aca7 | /src/user-interface/user-interface/arrangeable-tabs/model/quadgridlayoutpoint.cpp | 0aa85774c2f89d21871b0a400a47a05ea20e46db | [] | no_license | noodlecollie/calliper | f2299417bda8ec6c57eed08d8fdbae7a942c6267 | b23c945cdf24583a622a7b36954b6feb6314b018 | refs/heads/master | 2021-10-13T23:03:47.909959 | 2018-07-19T18:52:47 | 2018-07-19T18:52:47 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,754 | cpp | quadgridlayoutpoint.cpp | #include "quadgridlayoutpoint.h"
namespace UserInterface
{
QDebug operator <<(QDebug dbg, const QuadGridLayoutPoint& point)
{
dbg.nospace() << "QuadGridLayoutPoint(" << point.x() << "," << point.y() << ")";
return dbg.space();
}
QuadGridLayoutPoint::QuadGridLayoutPoint(int x, int y)
: m_iX(0), m_iY(0)
{
setX(x);
setY(y);
}
QuadGridLayoutPoint::QuadGridLayoutPoint(QuadGridLayoutDefs::GridCell cell)
: m_iX(0), m_iY(0)
{
setX(cell % 2);
setY(cell / 2);
}
int QuadGridLayoutPoint::x() const
{
return m_iX;
}
void QuadGridLayoutPoint::setX(int x)
{
m_iX = qBound(0, x, 1);
}
int QuadGridLayoutPoint::y() const
{
return m_iY;
}
void QuadGridLayoutPoint::setY(int y)
{
m_iY = qBound(0, y, 1);
}
int QuadGridLayoutPoint::toArrayIndex() const
{
return (2 * m_iY) + m_iX;
}
QuadGridLayoutPoint QuadGridLayoutPoint::neighbour(Qt::Orientation direction) const
{
return QuadGridLayoutPoint(direction == Qt::Horizontal ? (m_iX + 1) % 2 : m_iX,
direction == Qt::Vertical ? (m_iY + 1) % 2 : m_iY);
}
QuadGridLayoutPoint QuadGridLayoutPoint::diagonalNeighbour() const
{
return neighbour(Qt::Horizontal).neighbour(Qt::Vertical);
}
QuadGridLayoutDefs::GridCell QuadGridLayoutPoint::toCell() const
{
if ( m_iY == 0 )
{
return m_iX == 0 ? QuadGridLayoutDefs::NorthWest : QuadGridLayoutDefs::NorthEast;
}
else
{
return m_iX == 0 ? QuadGridLayoutDefs::SouthWest : QuadGridLayoutDefs::SouthEast;
}
}
}
|
176cd4e60dd3f261b9e64320906184abca01176e | 6c12dda9f7881b64f758597ce7262a16863a4c49 | /sorcery-provided-files/ascii_graphics.h | 2ead7f2e34237292ca164fc05d58104083ce3344 | [] | no_license | EricStratigakis/AsciiDungeonCrawler | 566d109d460aa677b6156b1fddb9350af8eff505 | 4cc7782ead514f7fc5cf77dd493bd277e33791cc | refs/heads/master | 2020-07-14T23:26:46.035128 | 2019-09-04T23:34:03 | 2019-09-04T23:34:03 | 205,426,233 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,238 | h | ascii_graphics.h | #include <vector>
#include <string>
//If SIMPLE_GRAPHICS = 1, use | and - instead of unicode and simplify graphics
//#define SIMPLE_GRAPHICS 1
typedef std::vector<std::string> card_template_t;
card_template_t display_minion_no_ability(std::string name,int cost,int attack,int defence);
card_template_t display_minion_triggered_ability(std::string name,int cost,int attack,int defence,
std::string trigger_desc);
card_template_t display_minion_activated_ability(std::string name,int cost,int attack,int defence,
int ability_cost, std::string ability_desc);
card_template_t display_ritual(std::string name,int cost,int ritual_cost,std::string ritual_desc,
int ritual_charges);
card_template_t display_spell(std::string name,int cost,std::string desc);
card_template_t display_enchantment_attack_defence(std::string name,int cost,std::string desc,
std::string attack,std::string defence);
card_template_t display_enchantment(std::string name,int cost,std::string desc);
card_template_t display_player_card(int player_num,std::string name,int life,int mana);
extern const card_template_t CARD_TEMPLATE_MINION_NO_ABILITY;
extern const card_template_t CARD_TEMPLATE_MINION_WITH_ABILITY;
extern const card_template_t CARD_TEMPLATE_BORDER;
extern const card_template_t CARD_TEMPLATE_EMPTY;
extern const card_template_t CARD_TEMPLATE_RITUAL;
extern const card_template_t CARD_TEMPLATE_SPELL;
extern const card_template_t CARD_TEMPLATE_ENCHANTMENT_WITH_ATTACK_DEFENCE;
extern const card_template_t CARD_TEMPLATE_ENCHANTMENT;
extern const card_template_t PLAYER_1_TEMPLATE;
extern const card_template_t PLAYER_2_TEMPLATE;
extern const std::vector<std::string> CENTRE_GRAPHIC;
extern const std::string EXTERNAL_BORDER_CHAR_UP_DOWN;
extern const std::string EXTERNAL_BORDER_CHAR_LEFT_RIGHT;
extern const std::string EXTERNAL_BORDER_CHAR_TOP_LEFT;
extern const std::string EXTERNAL_BORDER_CHAR_TOP_RIGHT;
extern const std::string EXTERNAL_BORDER_CHAR_BOTTOM_LEFT;
extern const std::string EXTERNAL_BORDER_CHAR_BOTTOM_RIGHT;
|
56c712a89b78d0fcc5564bcd77032f323c112e66 | 67ce5a6aa2f47053c460230b3d39266c06a82433 | /src/main.cpp | fb30d8e1b5576f596dcd42aa7d4d7bd20dd0f7c8 | [] | no_license | karolszymonczyk/Compiler | 512b33e9cae1c8cdc6f5307a17bb5db20ad47dff | 31104384fad0169e835b5d9c33cbf64ba0f1b1dc | refs/heads/master | 2022-09-10T03:22:26.182196 | 2020-01-25T11:23:48 | 2020-01-25T11:23:48 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 940 | cpp | main.cpp | #include <iostream>
#include <string>
#include "iofile.hpp"
#include "compiler.hpp"
extern int yyparse();
extern int yylineno;
extern FILE *yyin;
using namespace std;
int main(int argc, char **argv)
{
if (argc != 3)
{
cerr << "\033[1;31mError\033[0m incorrect args number" << endl;
exit(1);
}
string in_filename = argv[1];
string out_filename = argv[2];
yyin = read(in_filename);
if (yyin == NULL)
{
exit(1);
}
cout << "\n\33[1;37mCompiling...\33[0m" << endl;
int result = yyparse();
write(out_filename, code);
if (result == 0)
{
cout << "\n\033[1;32mCompilation completed successfully!\033[0m" << endl;
cout << "\33[1;37mExecuted lines: " << yylineno << "\33[0m\n"
<< endl;
}
else
{
cout << "\n\033[1;31mCompilation error\033[0m\n"
<< endl;
exit(1);
}
return 0;
} |
7221836356b08af3461f20cc1e3b3382d0504d24 | 122a397dec8d1ff9f3ba25c111af195809a34c37 | /Risk/Risk/StatisticsView.h | 375084483dd74c4719c2c967af4a9b911011d53a | [] | no_license | Teddy997/Risk | d74e1bbef02776fc4053faedf8f357eaf4d4a212 | 2b3aebf9213157451e6239816898ee84bf5d4960 | refs/heads/master | 2021-05-30T01:36:27.064999 | 2015-12-27T23:59:59 | 2015-12-27T23:59:59 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 275 | h | StatisticsView.h | #pragma once
#include "GameState.h"
#include <fstream>
class StatisticsView : public Observer
{
public:
StatisticsView();
~StatisticsView();
StatisticsView(GameState* game);
void Update();
void display();
GameState* getGameState();
private:
GameState* gameState;
};
|
fabab742b4c29cfc495d494d7de34ae364fec4af | 8595058be9a7db085b30380cb6110cff3ec8b357 | /tests/valueElement.cpp | a05aaa105a4a636441b0138d38960f071060de13 | [
"BSD-3-Clause"
] | permissive | steup/ASEIA | 622165a1a55491bd3f148bf1a231960c18cc10e6 | 498538fbefa95bac7723ad20582ff9d3dace3674 | refs/heads/master | 2021-03-27T16:21:51.479090 | 2018-07-18T23:40:55 | 2018-07-18T23:40:55 | 24,141,930 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,904 | cpp | valueElement.cpp |
#include <gtest/gtest.h>
#include <ValueElement.h>
namespace tests {
namespace valueElementSuite {
template<typename T, bool U>
bool exactlyEqual(const ValueElement<T, U>& a, const ValueElement<T, U>& b) {
return a.value() == b.value() && a.uncertainty() == b.uncertainty();
}
#define testComp(a, b, eq, ne, le, ge, lt, gt) { \
EXPECT_EQ(a==b, eq) << a << " == " << b << " = " << (a==b) << " != " << eq; \
EXPECT_EQ(a!=b, ne) << a << " != " << b << " = " << (a!=b) << " != " << ne; \
EXPECT_EQ(a<=b, le) << a << " <= " << b << " = " << (a<=b) << " != " << le; \
EXPECT_EQ(a>=b, ge) << a << " >= " << b << " = " << (a>=b) << " != " << ge; \
EXPECT_EQ(a<b, lt) << a << " < " << b << " = " << (a<b) << " != " << lt; \
EXPECT_EQ(a>b, gt) << a << " > " << b << " = " << (a>b) << " != " << gt; \
}
#define testOp(a, b, add, sub, mul, div) { \
EXPECT_TRUE(exactlyEqual(a+b, add)) << a << " + " << b << " = " << (a+b) << " != " << add; \
EXPECT_TRUE(exactlyEqual(a-b, sub)) << a << " - " << b << " = " << (a-b) << " != " << sub; \
EXPECT_TRUE(exactlyEqual(a*b, mul)) << a << " * " << b << " = " << (a*b) << " != " << mul; \
EXPECT_TRUE(exactlyEqual(a/b, div)) << a << " / " << b << " = " << (a/b) << " != " << div; \
}
TEST(ValueElementSuite, certainBoolTest) {
using V=ValueElement<bool, false>;
V e0 = {false};
V e1 = { true};
testComp(e0, e1, false, true , true, false, true , false);
testOp(e0, e1, e1, e0, e0, e0);
}
TEST(ValueElementSuite, uncertainBoolTest) {
using V=ValueElement<bool, false>;
V e0 = {false, false};
V e1 = { true, false};
V e2 = {false, true};
V e3 = { true, true};
testComp(e0, e1, false, true , true , false, true , false);
testOp(e0, e1, e1, e0, e0, e0);
testComp(e0, e2, true , false, true , true , false, false);
testOp(e0, e2, e2, e2, e0, e2);
testComp(e1, e3, true , false, true , true , false, false);
testOp(e1, e3, e3, e2, e3, e2);
}
TEST(ValueElementSuite, certainUInt8Test) {
using V=ValueElement<uint8_t, false>;
V e0 = { 0};
V e1 = {255};
V a = { 13};
V b = { 73};
V c = { 3};
testComp(a, b, false, true , true , false, true , false);
testComp(a, c, false, true , false, true , false, true );
testComp(b, c, false, true , false, true , false, true );
testOp(a, e0, a, a, V({ 0}), V({ 0}));
testOp(a, e1, V({255}), V({ 0}), V({255}), V({ 0}));
testOp(a, b, V({ 86}), V({ 0}), V({255}), V({ 0}));
testOp(a, c, V({ 16}), V({10}), V({ 39}), V({ 4}));
}
TEST(ValueElementSuite, certainInt8Test) {
using V=ValueElement<int8_t, false>;
V e0 = { 0};
V e1 = { 127};
V e2 = {-128};
V a = { 13};
V b = {- 73};
V c = { 3};
testComp(a, b, false, true , false, true , false, true );
testComp(a, c, false, true , false, true , false, true );
testComp(b, c, false, true , true , false, true , false);
testOp(a, e0, a, a, V({ 0}), V({ 0}));
testOp(a, e1, V({ 127}), V({-114}), V({ 127}), V({ 0}));
testOp(a, e2, V({-115}), V({ 127}), V({-128}), V({ 0}));
testOp(a, b, V({- 60}), V({ 86}), V({-128}), V({ 0}));
testOp(a, c, V({ 16}), V({ 10}), V({ 39}), V({ 4}));
}
TEST(ValueElementSuite, uncertainUInt8Test) {
using V=ValueElement<uint8_t, true>;
V e0 = {0, 0};
V e1 = {0, 255};
V e2 = {255, 0};
V e3 = {255, 255};
V a={13, 37};
V b={73, 1};
V c={3, 2};
testComp(a, b, false, true , true , false, true , false);
testComp(a, c, true , false, true , true , false, false);
testComp(b, c, false, true , false, true , false, true );
testOp(a, e0, a, a, V({0, 0}), V({0, 255}));
testOp(a, e1, V({13, 255}) , V({13, 255}), V({0, 255}) , V({0, 255}));
testOp(a, e2, V({255, 255}), V({0, 255}) , V({255, 255}), V({0, 1}) );
testOp(a, e3, V({255, 255}), V({0, 255}) , V({255, 255}), V({0, 255}));
testOp(a, b, V({86, 38}), V({0, 255}), V({255, 255}), V({0, 1}));
testOp(a, c, V({16, 39}), V({10, 39}), V({65, 185}), V({13, 37}));
}
TEST(ValueElementSuite, uncertainInt8Test) {
using V=ValueElement<int8_t, true>;
V e0 = {0, 0};
V e1 = {0, 255};
V e2 = {127, 0};
V e3 = {127, 255};
V e4 = {-128, 0};
V e5 = {-128, 255};
V a={13, 37};
V b={-73, 1};
V c={3, 2};
testComp(a, b, false, true , false, true , false, true );
testComp(a, c, true , false, true , true , false, false);
testComp(b, c, false, true , true , false, true , false);
testOp(a, e0, a, a, V({ 0, 0}), V({ 0, 255}));
testOp(a, e1, V({ 13, 255}), V({ 13, 255}), V({ 0, 255}), V({ 0, 255}));
testOp(a, e2, V({ 127, 255}), V({-114, 37}), V({ 127, 255}), V({ 0, 1}));
testOp(a, e3, V({ 127, 255}), V({-114, 255}), V({ 127, 255}), V({ 0, 255}));
testOp(a, e4, V({-115, 37}), V({ 127, 255}), V({-128, 255}), V({ 0, 1}));
testOp(a, e5, V({-115, 255}), V({ 127, 255}), V({-128, 255}), V({ 0, 255}));
testOp(a, b, V({- 60, 38}), V({ 86, 38}), V({-128, 255}), V({ 0, 1}));
testOp(a, c, V({ 16, 39}), V({ 10, 39}), V({ 65, 185}), V({13, 37}));
}
TEST(ValueElementSuite, castTest) {
using I8 = ValueElement<int8_t, true>;
using U8 = ValueElement<uint8_t, true>;
using U16 = ValueElement<uint16_t, true>;
using U32 = ValueElement<uint32_t, true>;
using F = ValueElement<float, true>;
using FC = ValueElement<float, false>;
using D = ValueElement<double, true>;
I8 i8 = {-127 , 0U };
U8 u8 = {255U , 0U };
U32 u32 = {1234U , 1U };
F f = {1234.5678f, 0.0f};
FC fc = {1234.5678f};
EXPECT_EQ(U8(i8).value(), 0U);
EXPECT_EQ(U8(i8).uncertainty(), 127U);
EXPECT_EQ(I8(u8).value(), 127);
EXPECT_EQ(I8(u8).uncertainty(), 128);
EXPECT_EQ(U16(f).value(), 1234U);
EXPECT_EQ(U16(f).uncertainty(), 1U);
EXPECT_EQ(U32(f).value(), 1234U);
EXPECT_EQ(U32(f).uncertainty(), 1U);
EXPECT_EQ(F(fc).value(), 1234.5678f);
EXPECT_EQ(F(fc).uncertainty(), 0.0f);
EXPECT_EQ(D(u32).value(), 1234);
EXPECT_EQ(D(u32).uncertainty(), 1);
}
}}
|
3f433e5e19b5aa049e1a24e6fe0bec6b48cd9476 | c1d39d3b0bcafbb48ba2514afbbbd6d94cb7ffe1 | /source/Stresser/BasicThread.h | 4bf0ef4658adb254e4bd30738cbf169a66b4c946 | [
"IJG",
"MIT"
] | permissive | P4ll/Pictus | c6bb6fbc8014c7de5116380f48f8c1c4016a2c43 | 0e58285b89292d0b221ab4d09911ef439711cc59 | refs/heads/master | 2023-03-16T06:42:12.293939 | 2018-09-13T18:19:30 | 2018-09-13T18:19:51 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 547 | h | BasicThread.h | #ifndef STRESSTEST_BASICTHREAD_H
#define STRESSTEST_BASICTHREAD_H
#include <memory>
#include <mutex>
#include <thread>
class BasicThread {
public:
void Run();
void Terminate();
BasicThread();
virtual ~BasicThread();
typedef std::shared_ptr<BasicThread> Ptr;
protected:
bool IsTerminating();
void Output(const std::string& s);
private:
void threadWrapper();
virtual void ThreadMain();
static size_t m_idThreadCounter;
std::mutex m_mutexTerm;
size_t m_id;
bool m_isTerminating;
std::shared_ptr<std::thread> m_thread;
};
#endif
|
aaf77eb361f0903639a5452f5110cc7c1fd7bf30 | deb6ab0c770228188e2c02d4315da31efb79661b | /Application/Main.cpp | 906022fd3fa17439592fb699e806c3da95d96d49 | [
"MIT"
] | permissive | jsj2008/OPengine | 27f2f661d77a43fbb95218ff0dddaba477fe51e6 | 1e509d04bfb3af8a14d3bcd27857abbc17143925 | refs/heads/master | 2021-01-22T08:47:33.360052 | 2017-05-17T00:33:56 | 2017-05-17T00:33:56 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,211 | cpp | Main.cpp | #include "ExampleSelectorState.h"
#ifdef ADDON_assimp
#include "./OPassimp.h"
#endif
#ifdef ADDON_libjpeg_turbo
#include "OPlibjpegturbo.h"
#endif
#ifdef ADDON_socketio
#include "OPsocketGamePadSystem.h"
#endif
//////////////////////////////////////
// Application Methods
//////////////////////////////////////
OPwindow mainWindow;
void ApplicationInit() {
TIMED_BLOCK;
OPcam _camera;
_camera.SetPerspective(OPvec3(0, 0, 5), OPvec3(0, 0, 0), OPvec3(0, 1, 0), 0.1f, 50.0f, 45.0f, 1920.0f / 1080.0f);
OPmat4 _proj = _camera.proj;
OPmat4 _view = _camera.view;
//OPlogToFile("output.txt");
OPCMAN.Init(OPIFEX_ASSETS);
OPloadersAddDefault();
OPscriptAddLoader();
OPskeletonAddLoader();
OPskeletonAnimationAddLoader();
SpineAddLoader();
#ifdef ADDON_assimp
OPassimpAddLoaders();
#endif
#ifdef ADDON_libjpeg_turbo
OPCMAN.AddLoader(&OPASSETLOADER_JPG);
#endif
OPoculusStartup();
OPrenderSetup();
OPwindowSystemInit();
mainWindow.Init(NULL, OPwindowParameters("Main Window", false, 1280, 720));
OPrenderInit(&mainWindow);
OPGAMEPADS.SetDeadzones(0.2f);
#ifdef ADDON_socketio
OPSOCKETGAMEPADS.Init();
OPSOCKETGAMEPADS.SetDeadzones(0.2f);
#endif
OPVISUALDEBUGINFO.Init();
OPgameState::Change(GS_EXAMPLE_SELECTOR);
}
OPint ApplicationUpdate(OPtimer* timer) {
if (mainWindow.Update()) {
return 1;
}
OPVISUALDEBUGINFO.Update(timer);
OPinputSystemUpdate(timer);
#ifdef ADDON_socketio
OPSOCKETGAMEPADS.Update(timer);
#endif
OPCMAN_UPDATE(timer);
if (OPKEYBOARD.WasReleased(OPkeyboardKey::ESCAPE)) return 1;
if ((OPKEYBOARD.WasReleased(OPkeyboardKey::BACKSPACE) || OPGAMEPADS[0]->WasPressed(OPgamePadButton::BACK)) && ActiveState != GS_EXAMPLE_SELECTOR) {
OPgameState::Change(GS_EXAMPLE_SELECTOR);
}
#ifdef ADDON_socketio
if ((OPSOCKETGAMEPADS[0]->WasPressed(OPgamePadButton::BACK)) && ActiveState != GS_EXAMPLE_SELECTOR) {
OPgameState::Change(GS_EXAMPLE_SELECTOR);
}
#endif
return ActiveState->Update(timer);
}
void ApplicationRender(OPfloat delta) {
ActiveState->Render(delta);
}
void ApplicationDestroy() {
ActiveState->Exit(ActiveState);
OPVISUALDEBUGINFO.Destroy();
OPCMAN.Destroy();
OPlogToFileClose();
mainWindow.Destroy();
}
void ApplicationSetup() {
OPinitialize = ApplicationInit;
OPupdate = ApplicationUpdate;
OPrender = ApplicationRender;
OPdestroy = ApplicationDestroy;
}
//////////////////////////////////////
// Application Entry Point
//////////////////////////////////////
#ifdef OPIFEX_IOS
#import <UIKit/UIKit.h>
#import "./Human/include/Rendering/AppDelegate.h"
int main(int argc, char * argv[]) {
@autoreleasepool {
return UIApplicationMain(argc, argv, nil, NSStringFromClass([AppDelegate class]));
}
}
#else
OP_MAIN_START
OPLOGLEVEL = (ui32)OPlogLevel::ERRORS;
#ifdef OPIFEX_OPTION_V8
// If the V8 engine is compiled in,
// see if we have a script to run at startup
//if(argc > 1) {
// //chdir(OPIFEX_ASSETS);
// OPjavaScriptV8SetupRun(args[2]);
// return 0;
//}
#endif
ApplicationSetup();
//OP_MAIN_RUN
OP_MAIN_RUN_STEPPED
OP_MAIN_END
#endif
|
8cad0c5f5408d21b8989fdde2185e54c5107b278 | e86bd8a18a34b6dfe66433cab921ea012fc900de | /f1006.cpp | a501d4d6291c3058b0fc8d1231590178877ef2a2 | [] | no_license | tingxueren/cstudy | 54f7828ced2eab8fd50282ea9dfbee2c3c1fe7fb | e3cd6f0e71a9478688b79f9c13fe0ebcef2c25ad | refs/heads/master | 2021-01-16T21:22:05.613662 | 2013-07-12T11:58:29 | 2013-07-12T11:58:29 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 664 | cpp | f1006.cpp | // f1006.cpp
// 多继承
#include<iostream>
using namespace std;
class Bed
{
protected:
int weight;
public:
Bed(): weight(0){}
void sleep()const{ cout << "Sleeping...\n";}
void setWeight(int i){ weight = i;}
};
class Sofa
{
protected:
int weight;
public:
Sofa():weight(0){}
void watchTV()const{ cout << "Watching TV.\n";}
void setWeight(int i){ weight = i;}
};
class SleeperSofa : public Bed, public Sofa
{
public:
SleeperSofa(){}
void foldOut()const{ cout << "Fold out the sofa.\n";}
};
int main()
{
SleeperSofa ss;
ss.watchTV();
ss.foldOut();
ss.sleep();
}
|
d4ee500304ea746e77fdf4bcd240084d963fd85d | 9c932aa68c918d0148445f5e4da6e41190bdeab1 | /agents_evolution_and_learning/techanalysis.cpp | 40c5a986345ffeb29ca31485f8ea74bdb95fd96d | [] | no_license | klakhman/agents_evolution_and_learning | 69fa5c2c9a8f676772e109c4d763c45d521e56e5 | 120a6f2735af079240d1931b3322431709f79231 | refs/heads/master | 2020-05-18T03:20:04.048054 | 2014-02-24T09:25:20 | 2014-02-24T09:25:20 | 5,669,375 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 47,399 | cpp | techanalysis.cpp | #include "techanalysis.h"
#include <vector>
#define _USE_MATH_DEFINES
#include "math.h"
#include <cmath>
#include <iostream>
#include <fstream>
#include <algorithm>
#include <functional>
#include <numeric>
#include <limits>
#include <sstream>
#include <ctime>
#include "TAgent.h"
#include "THypercubeEnvironment.h"
#include "TBehaviorAnalysis.h"
#include "RestrictedHypercubeEnv.h"
#include "settings.h"
#include "config.h"
#include <map>
using namespace std;
// Проверка разницы двух выброк по t-критерию (подрузамевается, что дисперсии выборок неизвестны и неравны - используется критерий Кохрена-Кокса для этого случая)
// Опциональные параметры - значения распределения Стьюдента с нужными степенями свобода и нужным уровнем значимости t_(alpha/2)(n-1)
// В случае, если опциональные параметры не передаются, то метод проводит сравнение выборок с уровнем значимости alpha = 0.01 и только в том случае, если размеры выборок равны 80, 100 или 120 - иначе всегда возвращает false
// Возвращает true - если средние неравны, false - если средние равны
bool techanalysis::tTestMeanDifference(const vector<double>& firstSequence, const vector<double>& secondSequence, double firstTValue /*=0*/, double secondTValue /*=0*/){
double firstMean = 0;
for (unsigned int i = 0; i < firstSequence.size(); ++i)
firstMean += firstSequence[i];
firstMean /= firstSequence.size();
double firstStandartDeviation = 0;
for (unsigned int i = 0; i < firstSequence.size(); ++i)
firstStandartDeviation += (firstSequence[i] - firstMean) * (firstSequence[i] - firstMean);
firstStandartDeviation /= (firstSequence.size() - 1);
double secondMean = 0;
for (unsigned int j = 0; j < secondSequence.size(); ++j)
secondMean += secondSequence[j];
secondMean /= secondSequence.size();
double secondStandartDeviation = 0;
for (unsigned int j = 0; j < secondSequence.size(); ++j)
secondStandartDeviation += (secondSequence[j] - secondMean) * (secondSequence[j] - secondMean);
secondStandartDeviation /= (secondSequence.size() - 1);
// Находим общее стандартное отклонение
double aggregateStandartDeviation = 1.0/firstSequence.size()*firstStandartDeviation + 1.0/secondSequence.size()*secondStandartDeviation;
double t_criteria = fabs(firstMean - secondMean)/sqrt(aggregateStandartDeviation);
// Подсчитываем критерий для сравнения (по методу Кохрена-Кокса)
if (!firstTValue){ // Если не задано значение распределения Стьюдента для первой выборки
if (80 == firstSequence.size()) firstTValue = 2.6380;
else if (100 == firstSequence.size()) firstTValue = 2.6259;
else if (120 == firstSequence.size()) firstTValue = 2.6174;
else return false;
}
if (!secondTValue){
if (80 == secondSequence.size()) secondTValue = 2.6380;
else if (100 == secondSequence.size()) secondTValue = 2.6259;
else if (120 == secondSequence.size()) secondTValue = 2.6174;
else return false;
}
double t_value = (firstStandartDeviation / firstSequence.size() * firstTValue + secondStandartDeviation / secondSequence.size() * secondTValue) /
(firstStandartDeviation / firstSequence.size() + secondStandartDeviation / secondSequence.size());
if (t_criteria > t_value)
return true;
else
return false;
}
// Критерий Колмогорова-Смирнова на принадлежность выборки нормальному распределению
// alpha - уровень значимости (с учетом используемых приближений alpha = {0.15; 0.10; 0.05; 0.03; 0.01})
bool techanalysis::testSampleNormality_KS(const vector<double>& sample, double alpha /*= 0.05*/){
vector<double> sorted_sample = sample;
sort(sorted_sample.begin(), sorted_sample.end());
// Находим среднее и отклонение
double mean = 0;
for (unsigned int currentValue = 0; currentValue < sorted_sample.size(); ++currentValue)
mean += sorted_sample[currentValue];
mean /= sorted_sample.size();
double variance = 0;
for (unsigned int currentValue = 0; currentValue < sorted_sample.size(); ++currentValue)
variance += (mean - sorted_sample[currentValue]) * (mean - sorted_sample[currentValue]);
variance = sqrt(variance / sorted_sample.size());
// Аппроксимируем нормальное распределение
// По формуле (Кобзарь, стр.28)
vector<double> normDistr(sorted_sample.size());
for (unsigned int currentValue = 0; currentValue < sorted_sample.size(); ++currentValue){
// Нормируем значение
double z = (sorted_sample[currentValue] - mean) / variance;
normDistr[currentValue] = 1.0/(1 + exp(-0.0725*abs(z)*(22+pow(abs(z), 1.96))));;
normDistr[currentValue] = (z >= 0) ? normDistr[currentValue] : (1 - normDistr[currentValue]);
}
// Теперь находим максимальные sup и inf множества отклонений эмпирической частоты от теоретической
double D_minus = -numeric_limits<double>::max();
double D_plus = -numeric_limits<double>::max();
for (unsigned int currentValue = 0; currentValue < sorted_sample.size(); ++currentValue){
D_plus = max(D_plus, (currentValue + 1) / static_cast<double>(sorted_sample.size()) - normDistr[currentValue]);
D_minus = max(D_minus, normDistr[currentValue] - currentValue / static_cast<double>(sorted_sample.size()));
}
// Используем модифицированную статистику (Кобзарь, стр.215)
double D = max(D_plus, D_minus) * (sqrt(static_cast<double>(sorted_sample.size())) - 0.01 + 0.85/sqrt(static_cast<double>(sorted_sample.size())));
// Используем точную формулу для нахождения критического значения (Кобзарь, стр.215)
// double D_crit = sqrt(1.0/(2.0*sorted_sample.size()) * (-log(alpha) - (2*log(alpha)*log(alpha) + 4*log(alpha) - 1)/(18.0 * sorted_sample.size()))) - 1.0 / (6.0 * sorted_sample.size());
// Для сравнения выборки с нормальным распределением с параметрами, выделенным из выборки нужно использовать данное критическое значение (Кобзарь, стр.233)
double D_crit = 0;
if (0.15 == alpha) D_crit = 0.775;
else if (0.1 == alpha) D_crit = 0.819;
else if (0.05 == alpha) D_crit = 0.895;
else if (0.03 == alpha) D_crit = 0.995;
else if (0.01 == alpha) D_crit = 1.035;
return (D < D_crit);
}
// Методика анализа стабильности группы нейронов, развивабщихся из пула - передается файл с сетью (геномом), которая эволюционировала с линейным системогенезом
// Подсчитывается средняя награда контроллера, полученного линейным системогенезом, и контроллера, полученного первичным системогенезом, если бы все пулы имели не единичный размер, а некоторый стандартный
vector<double> techanalysis::poolsStabilityAnalysis(string agentFilename, string environmentFilename, string settingsFilename, int poolsStandartCapacity /*=20*/, double developSynapseStandartProb /*=0.1*/){
int agentLifetime = 250;
// Итоговый вектор - первое значение это награда с линейным системогенезом, второе значение - с первичным системогенезом
vector<double> output;
// Загружаем агента и среду
TAgent agent;
ifstream agentFile;
agentFile.open(agentFilename.c_str());
agent.loadGenome(agentFile);
agentFile.close();
settings::fillAgentSettingsFromFile(agent, settingsFilename);
THypercubeEnvironment environment(environmentFilename);
settings::fillEnvironmentSettingsFromFile(environment, settingsFilename);
// Прогоняем сначала агента полученного в результате линейного системогенеза
agent.setSystemogenesisMode(0);
agent.setLearningMode(0);
environment.setStochasticityCoefficient(0.0);
int statesQuantity = environment.getInitialStatesQuantity();
agent.linearSystemogenesis();
double reward = 0;
for (int currentState = 0; currentState < statesQuantity; ++currentState){
environment.setEnvironmentState(currentState);
agent.life(environment, agentLifetime);
reward += agent.getReward();
}
output.push_back(reward/statesQuantity);
// Проверяем агента, полученного в результате первичного системогенеза
// Для этого надо сначала установить стандартные значения емкости пулов и вероятности развития связей
for (int currenPool = 1; currenPool <= agent.getPointerToAgentGenome()->getPoolsQuantity(); ++ currenPool){
if (TPoolNetwork::HIDDEN_POOL == agent.getPointerToAgentGenome()->getPoolType(currenPool))
agent.getPointerToAgentGenome()->setPoolCapacity(currenPool, poolsStandartCapacity);
for (int currentConnection = 1; currentConnection <= agent.getPointerToAgentGenome()->getPoolInputConnectionsQuantity(currenPool); ++currentConnection)
agent.getPointerToAgentGenome()->setConnectionDevelopSynapseProb(currenPool, currentConnection, developSynapseStandartProb);
}
agent.primarySystemogenesis();
reward = 0;
for (int currentState = 0; currentState < statesQuantity; ++currentState){
environment.setEnvironmentState(currentState);
agent.life(environment, agentLifetime);
reward += agent.getReward();
}
output.push_back(reward/statesQuantity);
return output;
}
// Процедура транспонирования записи данных
// На вход подается файл с данными расположенными по столбцам, на выходе файл с данными по строкам
// NB! : Kоличество отсчетов данных должно быть одинаково для всех столбцов
// В основном необходима для дальнешей отрисовки с помощью matplotlib
void techanalysis::transponceData(string inputFilename, string outputFilename, int columnsQuantity){
if (!columnsQuantity) return;
vector< vector<double> > data;
data.resize(columnsQuantity);
ifstream inputFile;
inputFile.open(inputFilename.c_str());
string dataString;
while (inputFile >> dataString) {
data[0].push_back(atof(dataString.c_str()));
for (int currentData = 1; currentData < columnsQuantity; ++currentData){
inputFile >> dataString;
data[currentData].push_back(atof(dataString.c_str()));
}
}
inputFile.close();
ofstream outputFile;
outputFile.open(outputFilename.c_str());
for (int currentData = 0; currentData < columnsQuantity; ++currentData){
for (unsigned int currentValue = 0; currentValue < data[currentData].size(); ++currentValue)
outputFile << data[currentData][currentValue] << "\t";
outputFile << "\n";
}
outputFile.close();
}
// Разбор файлов с результатами по анализу лучших популяций
vector<double> techanalysis::getValuesBPAFile(string bestPopulationAnalysisFile, int runsQuantity /*= 100*/){
string tmpStr;
vector<double> values;
ifstream inputFile;
inputFile.open(bestPopulationAnalysisFile.c_str());
for (int i = 0; i < runsQuantity; ++i){
inputFile >> tmpStr; // Считываем номер среды
inputFile >> tmpStr; // Считываем номер попытки
inputFile >> tmpStr; // Считываем награду
values.push_back(atof(tmpStr.c_str()));
}
inputFile.close();
return values;
}
// Удобная обертка для анализа на зависимость размера области сходимости стратегии от ее длины
// Создает файл с парами - (длина стратегии, размер области сходимости)
void techanalysis::analysisSLengthVsConvSize(string settingsFilename, string populationFilename, string environmentFilename, string outputFilename){
THypercubeEnvironment environment(environmentFilename);
settings::fillEnvironmentSettingsFromFile(environment, settingsFilename);
TPopulation<TAgent> agentsPopulation;
settings::fillPopulationSettingsFromFile(agentsPopulation, settingsFilename);
// Физически агенты в популяции уже созданы (после того, как загрузился размер популяции), поэтому можем загрузить в них настройки
settings::fillAgentsPopulationSettingsFromFile(agentsPopulation, settingsFilename);
agentsPopulation.loadPopulation(populationFilename);
vector< pair<int, int> > data = analysisSLengthVsConvSize(agentsPopulation, environment);
ofstream outFile;
outFile.open(outputFilename.c_str());
for (unsigned i=0; i < data.size(); ++i)
outFile << data[i].first << "\t" << data[i].second << endl;
outFile.close();
}
// Анализ на зависимость показателя размера областей сходимости стратегий от их длин (для одной популяции, циклы находятся независимо для каждого агента)
// Возвращает вектор пар - (длина стратегии, размер области сходимости)
vector< pair<int, int> > techanalysis::analysisSLengthVsConvSize(TPopulation<TAgent>& population, THypercubeEnvironment& environment){
environment.setStochasticityCoefficient(0.0);
vector< pair<int, int> > strategyLengthVsConvSize;
// Прогоняем всех агентов и находим соответствие длины цикла и его области сходимости
for (int agentNumber = 1; agentNumber <= population.getPopulationSize(); ++agentNumber){
TAgent& currentAgent = *population.getPointertoAgent(agentNumber);
currentAgent.linearSystemogenesis();
// Находим все стратегии агента и определяем размер их областей притяжения
vector< pair< TBehaviorAnalysis::SCycle, vector<int> > >convergenceData = calculateBehaviorConvergenceData(currentAgent, environment);
// Записываем найденные стратегии
for (unsigned int currentStrategy = 0; currentStrategy < convergenceData.size(); ++currentStrategy)
strategyLengthVsConvSize.push_back(make_pair(convergenceData[currentStrategy].first.cycleSequence.size(), convergenceData[currentStrategy].second.size()));
}
return strategyLengthVsConvSize;
}
// Анализ и подготовка данных для отображения развития в эволюции зависимости показателя размера областей сходимости стратегий от их длины
// На выходе файл с четыремя строками: 1) Длины стратегий; 2) Области сходимости стратегий; 3) Цвет даннных (в соответствии с номером эволюционного такта); 4) Соответствующий номер эволюционного такта
// Цветовая палитра: ранние такты - голубые, поздние - красные (через желтый и зеленый). Дальнейшая отрисовка происходит с помощью matplotlib.
void techanalysis::evolutionSLengthVsConvSize(string settingsFilename, string bestAgentsFilename, int evolutionTime,
string environmentFilename, string outputFilename, string colorPalette /*="RGB"*/){
vector< pair<int, int> > strategyLengthVsConvSize; // Соответствующие пары
vector<int> evolutionTacts; // Номера эволюционных тактов для всех пар
THypercubeEnvironment environment(environmentFilename);
settings::fillEnvironmentSettingsFromFile(environment, settingsFilename);
environment.setStochasticityCoefficient(0.0);
TAgent currentAgent;
settings::fillAgentSettingsFromFile(currentAgent, settingsFilename);
ifstream bestAgentsFile;
bestAgentsFile.open(bestAgentsFilename.c_str());
// Прогоняем всех лучших агентов и находим соответствие длины цикла и его области сходимости
for (int curEvolutionTime = 1; curEvolutionTime <= evolutionTime; ++curEvolutionTime){
currentAgent.loadGenome(bestAgentsFile);
currentAgent.linearSystemogenesis();
vector< pair< TBehaviorAnalysis::SCycle, vector<int> > > convergenceData = calculateBehaviorConvergenceData(currentAgent, environment);
// Записываем найденные стратегии
for (unsigned int currentStrategy = 0; currentStrategy < convergenceData.size(); ++currentStrategy){
strategyLengthVsConvSize.push_back(make_pair(convergenceData[currentStrategy].first.cycleSequence.size(), convergenceData[currentStrategy].second.size()));
evolutionTacts.push_back(curEvolutionTime);
}
cout << curEvolutionTime << endl;
}
bestAgentsFile.close();
// Записываем результаты
ofstream outputFile;
outputFile.open(outputFilename.c_str());
for (unsigned int currentStrategy = 0; currentStrategy < strategyLengthVsConvSize.size(); ++currentStrategy)
outputFile << strategyLengthVsConvSize[currentStrategy].first << "\t";
outputFile << endl;
for (unsigned int currentStrategy = 0; currentStrategy < strategyLengthVsConvSize.size(); ++currentStrategy)
outputFile << strategyLengthVsConvSize[currentStrategy].second << "\t";
outputFile << endl;
for (unsigned int currentStrategy = 0; currentStrategy < evolutionTacts.size(); ++currentStrategy)
outputFile << evolutionTacts[currentStrategy] << "\t";
outputFile << endl;
// Теперь записываем подготовленные цвета в нужной палитре (от голубого к красному через желтый и зеленый)
for (unsigned int currentStrategy = 0; currentStrategy < evolutionTacts.size(); ++currentStrategy){
double H = 360 * (0.5 - (0.5 * evolutionTacts[currentStrategy]) / evolutionTime); // Hue
double S = 0.9; // Saturation
double V = 0.9; // Brightness
if (colorPalette == "HSB")
outputFile << H << ";" << S << ";" << V << "\t";
else if (colorPalette == "RGB"){
int R, G, B;
service::HSVtoRGB(R, G, B, H, S, V);
string Rhex, Ghex, Bhex;
service::decToHex(R, Rhex, 2);
service::decToHex(G, Ghex, 2);
service::decToHex(B, Bhex, 2);
outputFile << "#" << Rhex + Ghex + Bhex << "\t";
}
}
outputFile.close();
}
// Проведение анализа по эволюции поведения на основе лучших агентов в каждой популяции
// Создает два файла: analysisOutputFileName - файл с парами (эв. такт; номер стратегии), обозначает присутствие стратегии в поведении агента на данном эв. такте;
// dataOutputFilename - файл со всеми стратегиями
// По умолчанию проводит анализ на основе циклов действий (при указании параметра true проводит анализ на основе циклов целей)
void techanalysis::conductBehaviorEvolutionAnalysis(string settingsFilename, string environmentFilename, string bestAgentsFilename, int evolutionTime,
string analysisOutputFilename, string dataOutputFilename, bool aimCycles /*=false*/){
THypercubeEnvironment environment(environmentFilename);
settings::fillEnvironmentSettingsFromFile(environment, settingsFilename);
environment.setStochasticityCoefficient(0.0);
TAgent currentAgent;
settings::fillAgentSettingsFromFile(currentAgent, settingsFilename);
ifstream bestAgentsFile;
bestAgentsFile.open(bestAgentsFilename.c_str());
ofstream analysisOutputFile;
analysisOutputFile.open(analysisOutputFilename.c_str());
vector<TBehaviorAnalysis::SCycle> cyclesData;
for (int curEvolutionTime = 1; curEvolutionTime <= evolutionTime; ++curEvolutionTime){
currentAgent.loadGenome(bestAgentsFile);
vector<TBehaviorAnalysis::SCycle> currentAgentCycles = TBehaviorAnalysis::findAllCyclesOfAgent(currentAgent, environment, aimCycles);
for (unsigned int currentCycle = 1; currentCycle <= currentAgentCycles.size(); ++currentCycle){
int cycleNumber = TBehaviorAnalysis::findCycleInExistingCycles(currentAgentCycles[currentCycle - 1], cyclesData);
if (cycleNumber) // Если такой цикл уже был
analysisOutputFile << curEvolutionTime << "\t" << cycleNumber << endl;
else{
cyclesData.push_back(currentAgentCycles[currentCycle - 1]);
analysisOutputFile << curEvolutionTime << "\t" << cyclesData.size() << endl;
}
}
cout << curEvolutionTime << "\t" << cyclesData.size() << endl;
}
bestAgentsFile.close();
analysisOutputFile.close();
TBehaviorAnalysis::uploadCycles(cyclesData, dataOutputFilename);
}
// Обертка для прогона популяции - возвращает средние награды (при запуске из всех состояний) для всех агентов в популяции.
// Системогенез проводится один раз для каждого агента. Если коэффициент стохастичности не указан, то берется значение из файла настроек.
vector<double> techanalysis::runPopulation(string populationFilename, string environmentFilename,
string settingsFilename, double stochasticityCoefficient /*=-1*/){
THypercubeEnvironment* environment = new THypercubeEnvironment(environmentFilename);
settings::fillEnvironmentSettingsFromFile(*environment, settingsFilename);
if (stochasticityCoefficient != -1)
environment->setStochasticityCoefficient(stochasticityCoefficient);
TPopulation<TAgent>* agentsPopulation = new TPopulation<TAgent>;
settings::fillPopulationSettingsFromFile(*agentsPopulation, settingsFilename);
// Физически агенты в популяции уже созданы (после того, как загрузился размер популяции), поэтому можем загрузить в них настройки
settings::fillAgentsPopulationSettingsFromFile(*agentsPopulation, settingsFilename);
agentsPopulation->loadPopulation(populationFilename);
return runPopulation(*agentsPopulation, *environment);
}
// Прогона популяции - возвращает средние награды (при запуске из всех состояний) для всех агентов в популяции.
// Системогенез проводится один раз для каждого агента. Если коэффициент стохастичности не указан, то берется значение из файла настроек.
vector<double> techanalysis::runPopulation(TPopulation<TAgent>& population, THypercubeEnvironment& environment){
vector<double> agentsRewards;
int initialStatesQuantity = environment.getInitialStatesQuantity();
// Прогоняем всех агентов и записываем награды в массив
for (int currentAgent = 1; currentAgent <= population.getPopulationSize(); ++currentAgent){
double averageReward = 0;
if (1 == population.getPointertoAgent(currentAgent)->getSystemogenesisMode())
population.getPointertoAgent(currentAgent)->primarySystemogenesis();
else if (0 == population.getPointertoAgent(currentAgent)->getSystemogenesisMode())
population.getPointertoAgent(currentAgent)->linearSystemogenesis();
else if (2 == population.getPointertoAgent(currentAgent)->getSystemogenesisMode())
population.getPointertoAgent(currentAgent)->alternativeSystemogenesis();
// Необходимо сохранять первичную нейронную сеть, так как запуск проходит из всех состояний и возможно обучение
TNeuralNetwork initialController;
if (0 != population.getPointertoAgent(currentAgent)->getLearningMode())
initialController = *(population.getPointertoAgent(currentAgent)->getPointerToAgentController());
for (int currentInitialState = 0; currentInitialState < initialStatesQuantity; ++currentInitialState){
if (0 != population.getPointertoAgent(currentAgent)->getLearningMode())
*(population.getPointertoAgent(currentAgent)->getPointerToAgentController()) = initialController;
environment.setEnvironmentState(currentInitialState);
population.getPointertoAgent(currentAgent)->life(environment, population.evolutionSettings.agentLifetime);
averageReward += population.getPointertoAgent(currentAgent)->getReward() / initialStatesQuantity;
}
agentsRewards.push_back(averageReward);
cout << currentAgent << "\t" << averageReward << endl;
}
return agentsRewards;
}
// Подсчет диаграммы сходимости поведения агента (возвращает пары - (поведенческий цикл действий, список состояний в бассейне притяжения поведенческой стратегии))
// ВАЖНО: агент уже должен иметь нейроконтроллер (т.е. пройти системогенез)
vector< pair< TBehaviorAnalysis::SCycle, vector<int> > > techanalysis::calculateBehaviorConvergenceData(TAgent& agent, THypercubeEnvironment& environment){
vector< pair< TBehaviorAnalysis::SCycle, vector<int> > > convergenceData;
vector< TBehaviorAnalysis::SCycle > agentStrategies;
environment.setStochasticityCoefficient(0.0);
// Так как может происходить обучение, то записываем изначальную сеть
TNeuralNetwork initialController = *(agent.getPointerToAgentController());
// Находим все стратегии агента и определяем размер их областей притяжения
for (int currentState = 0; currentState < environment.getInitialStatesQuantity(); ++currentState){
environment.setEnvironmentState(currentState);
TBehaviorAnalysis::SCycle currentStrategy = TBehaviorAnalysis::findCycleInAgentLife(agent, environment);
*(agent.getPointerToAgentController()) = initialController;
if (currentStrategy.cycleSequence.size()){
int strategyNumber = TBehaviorAnalysis::findCycleInExistingCycles(currentStrategy, agentStrategies);
if (strategyNumber) // Если такая стратегия уже была
convergenceData[strategyNumber - 1].second.push_back(currentState);
else{
agentStrategies.push_back(currentStrategy);
vector<int> tmp;
tmp.push_back(currentState);
convergenceData.push_back(make_pair(currentStrategy, tmp));
}
}
}
return convergenceData;
}
// Анализ прироста количества включающихся нейронов при обучения в зависимости от разницы награды при прогоне с обучением и без
void techanalysis::conductLearningVsNonLearningAnalysis(TAgent& agent, THypercubeEnvironment& environment, string outputFilename,
int runsQuantity /*=200*/, int agentLifetime /*=100*/){
ofstream outputFile;
outputFile.open(outputFilename.c_str());
environment.setStochasticityCoefficient(0.0);
for (int currentRun = 0; currentRun < runsQuantity; ++currentRun){
agent.primarySystemogenesis();
agent.setLearningMode(1);
double averageDiffNeurons = 0;
int initNeurons = agent.getActiveNeuronsQuantity();
double averageLearningReward = 0;
TNeuralNetwork initController = *(agent.getPointerToAgentController());
for (int currentState = 0; currentState < environment.getInitialStatesQuantity(); ++currentState){
environment.setEnvironmentState(currentState);
*(agent.getPointerToAgentController()) = initController;
agent.life(environment, agentLifetime);
averageLearningReward += agent.getReward() / environment.getInitialStatesQuantity();
averageDiffNeurons += (agent.getActiveNeuronsQuantity() - initNeurons)/static_cast<double>(environment.getInitialStatesQuantity());
}
*(agent.getPointerToAgentController()) = initController;
double averageNonLearningReward = 0;
agent.setLearningMode(0);
for (int currentState = 0; currentState < environment.getInitialStatesQuantity(); ++currentState){
environment.setEnvironmentState(currentState);
agent.life(environment, agentLifetime);
averageNonLearningReward += agent.getReward() / environment.getInitialStatesQuantity();
}
cout << currentRun << ":\t" << averageLearningReward << "\t" << (averageLearningReward - averageNonLearningReward) << "\t" << averageDiffNeurons << endl;
outputFile << averageLearningReward << "\t" << (averageLearningReward - averageNonLearningReward) << "\t" << averageDiffNeurons << endl;
}
}
// Отрисовка с помощью утилиты dot пакета GraphViz "поведенческой карты" агента (бассейнов притяжения различных поведенческих стратегий)
void techanalysis::makeBehaviorConvergenceDiagram(TAgent& agent, THypercubeEnvironment& environment, string imageFilename){
vector< pair< TBehaviorAnalysis::SCycle, vector<int> > > convergenceData = calculateBehaviorConvergenceData(agent, environment);
double sizeScaleCoef = 0.1; // Масштабирование размера круга в зависимости от длины цикла
ofstream outputDotFile;
outputDotFile.open((imageFilename + ".dot").c_str());
outputDotFile << "graph G{" << endl << "dpi = \"600\";" << endl;
// Необходимо дополнительно определить состояния, из которых агент никуда не сходится
vector<bool> noCycleStatesInd(environment.getInitialStatesQuantity(), false);
for (unsigned int currentCycle = 1; currentCycle <= convergenceData.size(); ++currentCycle){
double circleSize = convergenceData[currentCycle - 1].first.cycleSequence.size() * sizeScaleCoef;
string color = "grey60";
outputDotFile << "\tc" << currentCycle << " [label=\"" << currentCycle << "\", shape=doublecircle, fillcolor=" << color
<< ", style=filled, height=" << circleSize << ", fixedsize=true]" << endl;
// Записываем бассейн притяжения
for (unsigned int currentState = 1; currentState <= convergenceData[currentCycle - 1].second.size(); ++currentState){
int stateNumber = convergenceData[currentCycle - 1].second[currentState - 1];
outputDotFile << "\ts" << stateNumber << " [label = \"" << stateNumber << "\", fontname=\"Arial\"]" << endl;
outputDotFile << "\ts" << stateNumber << " -- c" << currentCycle << endl;
noCycleStatesInd[stateNumber] = true;
}
}
vector<int> noCycleStates;
for (unsigned int currenState = 0; currenState < noCycleStatesInd.size(); ++currenState)
if (!noCycleStatesInd[currenState]) noCycleStates.push_back(currenState);
// Если есть хотя бы одно состояние, из которого агент никуда не сходится
if (noCycleStates.size()){
outputDotFile << "\tc0 [height=0, fixedsize=true]" << endl;
for (unsigned int currentState = 1; currentState <= noCycleStates.size(); ++currentState){
int stateNumber = noCycleStates[currentState - 1];
outputDotFile << "\ts" << stateNumber << " [label = \"" << stateNumber << "\", fontname=\"Arial\"]" << endl;
outputDotFile << "\ts" << stateNumber << " -- c0" << endl;
}
}
outputDotFile << "}" << endl;
// Записываем циклы
vector<TBehaviorAnalysis::SCycle> cycles;
for (unsigned int currentCycle = 0; currentCycle < convergenceData.size(); ++currentCycle)
cycles.push_back(convergenceData[currentCycle].first);
TBehaviorAnalysis::uploadCycles(cycles, imageFilename + ".txt");
// Отрисовываем картинку
system(("fdp -Tjpg " + imageFilename + ".dot -o " + imageFilename).c_str());
}
// Возвращает эмпирическое значение плотности целей для среды (рассчитывается путем прогона случайных агентов на среде)
double techanalysis::empiricalGD(THypercubeEnvironment& environment, int runsQuantity/*=250*/, int agentLifeTime/*=400*/){
double empiricalGD = 0;
for (int currentRun = 0; currentRun < runsQuantity; ++currentRun){
environment.setRandomEnvironmentState();
vector< vector<double> > agentLife(agentLifeTime);
int goalsReached = 0;
// Жизнь одного агента
for (int currentLifestep = 1; currentLifestep <= agentLifeTime; ++currentLifestep){
// Определяем случайное действие агента (отличное от нуля)
double action = 0;
while (!action){
action = static_cast<double>(service::uniformDiscreteDistribution(-environment.getEnvironmentResolution(), environment.getEnvironmentResolution()));
}
agentLife[currentLifestep - 1].push_back(action);
// Действуем на среду и проверяем успешно ли действие
bool actionSuccess = (environment.forceEnvironment(agentLife[currentLifestep - 1]) != 0);
if (!actionSuccess) agentLife[currentLifestep - 1][0] = 0;
// Определяем количество целей достигнутых на данном шаге
//goalsReached += environment.testReachingAims(agentLife, currentLifestep).size();
}
empiricalGD += environment.calculateReward(agentLife, agentLifeTime) / (agentLifeTime * runsQuantity);//(goalsReached / static_cast<double>(agentLifeTime)) / runsQuantity;
}
return empiricalGD;
}
// Эмпирическая проверка коэффициента плотности целей в среде
// Проверка проводится путем запуска случайного агента в среду на фиксированное время (все действия агента равновероятны) и подсчета количества достигнутых целей
void techanalysis::empiricalCheckGD(string environmentDirectory, int firstEnvNumber, int lastEnvNumber, string resultsFile){
srand(static_cast<unsigned int>(time(0)));
ofstream outputFile(resultsFile.c_str());
outputFile << "Environment number\tTheoretical GD\tEmpirical GD" << endl;
stringstream environmentFilename;
const int runsQuantity = 400;
const int agentLifeTime = 600;
for (int currentEnvironment = firstEnvNumber; currentEnvironment <= lastEnvNumber; ++currentEnvironment){
environmentFilename.str("");
environmentFilename << environmentDirectory << "/Environment" << currentEnvironment << ".txt";
THypercubeEnvironment environment(environmentFilename.str());
double averageGD = empiricalGD(environment, runsQuantity, agentLifeTime);
outputFile << currentEnvironment << "\t" << environment.calculateOccupancyCoefficient() << "\t" << averageGD << endl;
}
outputFile.close();
}
void parseCommandLine(int argc, char** argv, vector<string> parametersNames, map<string, pair<string, void*> > parameters){
int currentArgNumber = 1; // Текущий номер параметра
while (currentArgNumber < argc){
if (argv[currentArgNumber][0] == '-'){ // Если это название настройки
for (unsigned int currentParam = 0; currentParam < parametersNames.size(); ++currentParam)
if (parametersNames[currentParam] == argv[currentArgNumber]){
pair<string, void*>& paramProperties = parameters[parametersNames[currentParam]];
if (paramProperties.first == "int") *static_cast<int*>(paramProperties.second) = atoi(argv[++currentArgNumber]);
else if (paramProperties.first == "double") *static_cast<double*>(paramProperties.second) = atof(argv[++currentArgNumber]);
else if (paramProperties.first == "string") *static_cast<string*>(paramProperties.second) = argv[++currentArgNumber];
else if (paramProperties.first == "bool") *static_cast<bool*>(paramProperties.second) = (atoi(argv[++currentArgNumber]) != 0);
break;
}
}
++currentArgNumber;
}
}
// Обертка для проведения анализа топологии агентов лучших популяций
// Передается ссылка на функцию, которая принимает агента и возвращает вектор значений (напр. кол-во нейронов, кол-во синапсов и т.д.)
void statisticsOnAgents(int argc, char** argv, vector<double> (*statFunc)(TAgent& agent)){
// Расшифровываем параметры командной строки
string settingsFilename = settings::getSettingsFilename(argc, argv);
int currentArgNumber = 1; // Текущий номер параметра
int firstEnvironmentNumber, lastEnvironmentNumber, firstTryNumber, lastTryNumber;
string runSign, outputFilename;
while (currentArgNumber < argc){
if (argv[currentArgNumber][0] == '-'){ // Если это название настройки
if (!strcmp("-env", argv[currentArgNumber])) { firstEnvironmentNumber = atoi(argv[++currentArgNumber]); lastEnvironmentNumber = atoi(argv[++currentArgNumber]);}
else if (!strcmp("-try", argv[currentArgNumber])) { firstTryNumber = atoi(argv[++currentArgNumber]); lastTryNumber = atoi(argv[++currentArgNumber]);}
else if (!strcmp("-sign", argv[currentArgNumber])) { runSign = argv[++currentArgNumber]; }
else if (!strcmp("-outf", argv[currentArgNumber])) { outputFilename = argv[++currentArgNumber]; }
}
++currentArgNumber;
}
ofstream outputFile(outputFilename.c_str());
string workDirectory, environmentDirectory, resultsDirectory;
settings::fillDirectoriesSettings(workDirectory, environmentDirectory, resultsDirectory, settingsFilename);
stringstream tmpStream;
for (int currentEnv = firstEnvironmentNumber; currentEnv <= lastEnvironmentNumber; ++currentEnv){
for (int currentTry = firstTryNumber; currentTry <= lastTryNumber; ++currentTry){
tmpStream.str(""); // Очищаем поток
tmpStream << resultsDirectory << "/En" << currentEnv << "/En" << currentEnv << "_" << runSign << "(" << currentTry << ")_bestpopulation.txt";
string bestPopulationFilename = tmpStream.str();
}
}
}
/// Конструирование среды с "перевернутыми" целями, относительно исходной
void reverseEnvironment(const THypercubeEnvironment& environment, string outputFilename){
unsigned int aimsQuantity = environment.getAimsQuantity();
ofstream outputFile(outputFilename.c_str());
outputFile << environment.getEnvironmentResolution() << "\t" << aimsQuantity << endl;
for (unsigned int aimN = 0; aimN < aimsQuantity; ++aimN){
const THypercubeEnvironment::TAim& aim = environment.getAimReference(aimN + 1);
outputFile << aim.aimComplexity << "\t" << aim.reward << endl;
for (unsigned int action = 0; action < aim.aimComplexity; ++action)
outputFile << (aim.actionsSequence[aim.aimComplexity - 1 - action].desiredValue ? 1 : -1) *
aim.actionsSequence[aim.aimComplexity - 1 - action].bitNumber << "\t";
outputFile << endl;
}
outputFile.close();
}
inline double sum(const vector<double>& vec){
return accumulate(vec.begin(), vec.end(), 0.0, plus<double>());
}
vector<double> techanalysis::totalRun(TAgent& agent, THypercubeEnvironment& environment, unsigned int lifetime /*=250*/){
const unsigned int statesQ = environment.getInitialStatesQuantity();
vector<double> runs(statesQ);
TNeuralNetwork controller;
if (agent.getLearningMode())
controller = *agent.getPointerToAgentController();
for (unsigned int state = 0; state < statesQ; ++state){
if (agent.getLearningMode())
*agent.getPointerToAgentController() = controller;
environment.setEnvironmentState(state);
agent.life(environment, lifetime);
runs.at(state) = agent.getReward();
}
return runs;
}
// Анализ на эволюцию разницы награды с обучением и без (с дискретизацией) (envType - 0 (обычная среда гиперкуб), 1 (ограниченная среда))
void techanalysis::difEvolutionAnalysis(const string& bestAgentsFilename, unsigned int evolTime, const string& environmentFilename, unsigned int envType,
const string& settingsFilename, const string& resultsFilename, unsigned int evolDiscr /*=50*/,
unsigned int sysNumber /*=5*/, unsigned int lifetime /*=100*/){
THypercubeEnvironment* environment;
switch (envType){
case 0:
environment = new THypercubeEnvironment(environmentFilename);
break;
case 1:
environment = new RestrictedHypercubeEnv(environmentFilename);
break;
}
settings::fillEnvironmentSettingsFromFile(*environment, settingsFilename);
environment->setStochasticityCoefficient(0.0);
TAgent agent;
settings::fillAgentSettingsFromFile(agent, settingsFilename);
const unsigned int bins = evolTime / evolDiscr;
ofstream results(resultsFilename.c_str());
unsigned int learningMode = agent.getLearningMode();
for (unsigned int bin = 0; bin < bins; ++bin){
agent.loadGenome(bestAgentsFilename, bin * evolDiscr + 1);
double rewardWithLearning = 0;
double rewardWithoutLearning = 0;
for (unsigned int run = 0; run < sysNumber; ++run){
agent.systemogenesis();
agent.setLearningMode(0);
vector<double> rewardsWithoutLearning = totalRun(agent, *environment, lifetime);
rewardWithoutLearning += sum(rewardsWithoutLearning) / (sysNumber * rewardsWithoutLearning.size());
agent.setLearningMode(learningMode);
vector<double> rewardsWithLearning = totalRun(agent, *environment, lifetime);
rewardWithLearning += sum(rewardsWithLearning) / (sysNumber * rewardsWithLearning.size());
}
results << bin * evolDiscr + 1 << "\t" << rewardWithLearning << "\t" << rewardWithoutLearning << endl;
cout << bin * evolDiscr + 1 << "\t" << rewardWithLearning << "\t" << rewardWithoutLearning << endl;
}
delete environment;
results.close();
}
#ifndef NOT_USE_ALGLIB_LIBRARY
#include "statistics.h"
// Обертка над функцией из ALGLIB - тестирование нормальности выборки по методу Харки — Бера.
// Возвращает p-value. Чем оно больше - тем лучше, как минимум должно быть выше 0.05.
double testSampleNormality_JB_ALGLIB(const std::vector<double>& sample){
alglib::real_1d_array _sample;
_sample.setcontent(sample.size(), &(sample[0]));
double p_value;
alglib::jarqueberatest(_sample, sample.size(), p_value);
return p_value;
}
// Обертка над функцией из ALGLIB - тестирование разницы средних двух _НОРМАЛЬНЫХ_ выборок по критерию Стьюдента.
// Возвращает p-value для two-tailed теста. Разница между средними есть, если p-value меньше заданного уровня значимости.
double tTestMeanDifference_ALGLIB(const std::vector<double>& firstSample, const std::vector<double>& secondSample){
alglib::real_1d_array _firstSample;
_firstSample.setcontent(firstSample.size(), &(firstSample[0]));
alglib::real_1d_array _secondSample;
_secondSample.setcontent(secondSample.size(), &(secondSample[0]));
double p_value, p_left, p_right;
alglib::unequalvariancettest(_firstSample, firstSample.size(), _secondSample, secondSample.size(), p_value, p_left, p_right);
return p_value;
}
// Обертка над функцией из ALGLIB - тестирование разницы средних двух выборок по критерию Манна-Уитни.
// Возвращает p-value для two-tailed теста. Разница между средними есть, если p-value меньше заданного уровня значимости.
double mann_whitneyMeanDifference_ALGLIB(const std::vector<double>& firstSample, const std::vector<double>& secondSample){
alglib::real_1d_array _firstSample;
_firstSample.setcontent(firstSample.size(), &(firstSample[0]));
alglib::real_1d_array _secondSample;
_secondSample.setcontent(secondSample.size(), &(secondSample[0]));
double p_value, p_left, p_right;
alglib::mannwhitneyutest(_firstSample, firstSample.size(), _secondSample, secondSample.size(), p_value, p_left, p_right);
return p_value;
}
#endif
|
3e1d78b0fec4a041bb9940d8d7eea94739edcb9b | 43a75749adaed18926456a079640e78c524761d4 | /set2/c_10.cpp | 7d37681509404e36ba1ea3b1d76ca01bb0bf8733 | [] | no_license | guybaryosef/cryptopals | 5dd023fb1adb578fb46fd8e357292a22a4a4ae3e | c09e39982b73a6002ffa1da79eb181c80601dd34 | refs/heads/master | 2018-07-07T05:04:23.211686 | 2018-06-18T01:38:36 | 2018-06-18T01:38:36 | 115,704,849 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,724 | cpp | c_10.cpp | /*
Cryptopals Crypto Challenges
Set 2
Challenge 10 - Implement CDC mode
By: Guy Bar Yosef
*/
#include "functions2.cpp"
int main() {
//testing the decrypt CBC function using the provided input file 'c_10input.txt' and outputing in 'c_10output.txt'.
unsigned char inputKey[] = "YELLOW SUBMARINE";
string inputf = "c_10input.txt";
char IV[] = "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00";
ifstream input_file(inputf);
assert(input_file && "unable to open file :{");
Bin bininput;
Base64 buf1;
while (getline(input_file, buf1.val))
bininput.val.append( buf1.toBin() );
string temp = bininput.toString();
unsigned char input[temp.length()+1]; // containes the encrypted string from the input file
for (int i = 0 ; i < temp.length() ; ++i)
input[i] = temp[i];
input[temp.length()] = '\0';
unsigned char output[temp.length()+1]; // will contain the decyphered text
output[temp.length()] = '\0';
decryptAES128inCBC(IV, input, inputKey, output, temp.length() );
ofstream output_file("c_10output.txt");
output_file << output << endl;
input_file.close();
output_file.close();
////////////////////////////////////////
// encrypting and decrypting my own file, 'c_10input2.txt', and outputing the result as 'c_10output2.txt'.
////////////////////////////////////////
input_file.open("c_10input2.txt");
assert(input_file && "unable to open file :{");
output_file.open("c_10output2.txt");
assert(output_file && "Cannot create/overwrite output file :{");
string buffer;
string totalinput;
while (getline(input_file, buffer))
totalinput.append( buffer+ "\n");
output_file << "Original Message: " << endl << totalinput << endl;
totalinput = implementPKSC7(totalinput, AES_BLOCK_SIZE); // pad the plaintext
unsigned char input2[totalinput.length()+1]; // the input of the plaintext file
for (int i = 0 ; i < totalinput.length() ; ++i)
input2[i] = totalinput[i];
input2[totalinput.length()] = '\0';
unsigned char encryptedText[totalinput.length() +1]; // the outputted encrypted text
encryptedText[totalinput.length()] = '\0';
encryptAES128inCBC(IV, input2, inputKey, encryptedText, totalinput.length());
output_file << "\n\n" << "Encrypted Message: " << endl << encryptedText << endl;
unsigned char decryptedText[totalinput.length()+1];
decryptedText[totalinput.length()] = '\0';
decryptAES128inCBC(IV, encryptedText, inputKey, decryptedText, totalinput.length() );
output_file << "\n\n" << "Decrypted message: " << endl << decryptedText << endl;
return 0;
}
|
5ac39d29399bba874f1a653168c5f30cbefa44c8 | d1d0d82210de4b2a4a500b2a934244fe51f8ab4c | /CLogic.hpp | 59bbc1d62e2d05d07e6882a7362b28a3602129a8 | [] | no_license | logitec1994/Tankz | 5fd028015904401899c3ebb5e4f5d2b551178ea8 | 857d5a7fa53db8560aea572d822e85f95456dc72 | refs/heads/master | 2020-03-19T14:06:51.673594 | 2019-09-26T23:47:34 | 2019-09-26T23:47:34 | 136,609,191 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 206 | hpp | CLogic.hpp | #ifndef CLOGIC_HPP
#define CLOGIC_HPP
class CLogic
{
public:
CLogic();
~CLogic();
void move_left();
void move_right();
void move_up();
void move_down();
void shoot();
};
#endif |
c8c23a21fddeea97c85ec26c0611a917ad000e04 | a5b0e75e0b44acef19e37ce15cda4af0f46f2afe | /Source/NetworkedRPG/Private/Items/Actors/NRangedWeaponActor.cpp | a5589aee206b18b5a267082f1b1189dc62218528 | [] | no_license | mikegreber/NetworkedRPG | 33c419e492599799a82479bc81df1145a6ee7800 | 1b9fd7346d010c1477e3d533b94e37bacdbf0691 | refs/heads/master | 2022-12-20T03:39:49.755720 | 2020-10-04T21:07:53 | 2020-10-04T21:07:53 | 283,267,032 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,663 | cpp | NRangedWeaponActor.cpp | // Fill out your copyright notice in the Description page of Project Settings.
#include "Items/Actors/NRangedWeaponActor.h"
#include "AbilitySystem/NAbilitySystemComponent.h"
#include "AbilitySystem/Targeting/NGATA_LineTrace.h"
#include "Characters/NCharacterBase.h"
#include "Net/UnrealNetwork.h"
ANRangedWeaponActor::ANRangedWeaponActor() : ANWeaponActor()
{
}
void ANRangedWeaponActor::GetLifetimeReplicatedProps(TArray<FLifetimeProperty>& OutLifetimeProps) const
{
Super::GetLifetimeReplicatedProps(OutLifetimeProps);
DOREPLIFETIME_CONDITION(ANRangedWeaponActor, ClipAmmo, COND_OwnerOnly);
DOREPLIFETIME_CONDITION(ANRangedWeaponActor, MaxClipAmmo, COND_OwnerOnly);
}
void ANRangedWeaponActor::PreReplication(IRepChangedPropertyTracker& ChangedPropertyTracker)
{
Super::PreReplication(ChangedPropertyTracker);
DOREPLIFETIME_ACTIVE_OVERRIDE(ANRangedWeaponActor, ClipAmmo, (IsValid(AbilitySystemComponent) && !AbilitySystemComponent->HasMatchingGameplayTag(WeaponIsFiringTag)));
}
void ANRangedWeaponActor::SetClipAmmo(int32 NewClipAmmo)
{
int32 OldClipAmmo = ClipAmmo;
ClipAmmo = NewClipAmmo;
OnClipAmmoChanged.Broadcast(OldClipAmmo, ClipAmmo);
}
void ANRangedWeaponActor::SetMaxClipAmmo(int32 NewMaxClipAmmo)
{
int32 OldMaxClipAmmo = MaxClipAmmo;
MaxClipAmmo = NewMaxClipAmmo;
OnMaxClipAmmoChanged.Broadcast(OldMaxClipAmmo, MaxClipAmmo);
}
void ANRangedWeaponActor::OnRep_ClipAmmo(int32 OldClipAmmo)
{
OnClipAmmoChanged.Broadcast(OldClipAmmo, ClipAmmo);
}
void ANRangedWeaponActor::OnRep_MaxClipAmmo(int32 OldMaxClipAmmo)
{
OnMaxClipAmmoChanged.Broadcast(OldMaxClipAmmo, MaxClipAmmo);
}
|
782ad4504b2f8c7f50dbd4bb4463fb4b9b531b0a | 80b3261c58d4fd364178ee2eefb2db29c192f303 | /Data Structure/2528.cpp | 3dcaff054f9063d7ba94bc0823ab74d849bf0f88 | [] | no_license | TschieM/poj | a473fc43db43912af8bd3d10293c062d55692374 | 5538a3b88cb0db57b1de9b69872a6a162b6bc64a | refs/heads/master | 2020-04-01T04:18:39.209263 | 2018-11-25T16:07:01 | 2018-11-25T16:07:01 | 152,853,710 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,343 | cpp | 2528.cpp | /*
Description
The citizens of Bytetown, AB, could not stand that the candidates in the mayoral
election campaign have been placing their electoral posters at all places at their
whim. The city council has finally decided to build an electoral wall for placing
the posters and introduce the following rules:
~ Every candidate can place exactly one poster on the wall.
~ All posters are of the same height equal to the height of the wall; the width of
a poster can be any integer number of bytes (byte is the unit of length in Bytetown).
~ The wall is divided into segments and the width of each segment is one byte.
~ Each poster must completely cover a continuous number of wall segments.
They have built a wall 10000000 bytes long (such that there is enough place for
all candidates). When the electoral campaign was restarted, the candidates were
placing their posters on the wall and their posters differed widely in width.
Moreover, the candidates started placing their posters on wall segments already
occupied by other posters. Everyone in Bytetown was curious whose posters will be
visible (entirely or in part) on the last day before elections.
Your task is to find the number of visible posters when all the posters are placed
given the information about posters' size, their place and order of placement on
the electoral wall.
Input
The first line of input contains a number c giving the number of cases that follow.
The first line of data for a single case contains number 1 <= n <= 10000. The
subsequent n lines describe the posters in the order in which they were placed.
The i-th line among the n lines contains two integer numbers li and ri which are
the number of the wall segment occupied by the left end and the right end of the
i-th poster, respectively. We know that for each 1 <= i <= n, 1 <= li <= ri <= 10000000.
After the i-th poster is placed, it entirely covers all wall segments numbered
li, li+1 ,... , ri.
Output
For each input data set print the number of visible posters after all the posters
are placed.
Sample Input Sample Output
1 4
5
1 4
2 6
8 10
3 4
7 10
*/
#include <iostream>
#include <algorithm>
#define MAXN 40010
using namespace std;
void update(int node, int ql, int qr, int val, int l, int r);
void query(int node, int ql, int qr, int l, int r);
bool fcmp(int i, int j);
int C, N, nump;
int ar[MAXN], idx[MAXN], dis[MAXN<<1];
int tree[MAXN<<3], lazy[MAXN<<3], cnt[MAXN<<3];
bool mark[MAXN<<1];
int main() {
cin >> C;
while(C--) {
for (int i=0; i<(MAXN<<3); i++) {
if (i < (MAXN<<1)) mark[i] = false;
tree[i] = 0;
lazy[i] = 0;
cnt[i] = 0;
}
cin >> N;
// 数据离散化
for (int i=1; i<=N; i++) {
cin >> ar[(i<<1)-1] >> ar[i<<1];
idx[(i<<1)-1] = (i<<1)-1;
idx[i<<1] = (i<<1);
}
sort(idx+1, idx+(N<<1)+1, fcmp);
for (int i=1; i<=(N<<1); i++) {
if (i == 1) dis[idx[1]] = 1;
else dis[idx[i]] = dis[idx[i-1]] +
((ar[idx[i]]-ar[idx[i-1]]<=1)?(ar[idx[i]]-ar[idx[i-1]]):2);
}
// 区间跟新线段树tree
for (int i=1; i<=N; i++) {
update(1, dis[(i<<1)-1], dis[i<<1], i, 1, MAXN);
}
// 查询tree有多少个不同的数
nump = 0;
query(1, 1, MAXN<<1, 1, MAXN<<1);
cout << nump << endl;
}
return 0;
}
void update(int node, int ql, int qr, int val, int l, int r) {
if (ql>r || qr<l) return ;
if (lazy[node]) {
tree[node] = lazy[node];
lazy[node<<1] = tree[node];
lazy[node<<1|1] = tree[node];
lazy[node] = 0;
}
if (ql<=l && qr>=r) {
tree[node] = val;
lazy[node<<1] = tree[node];
lazy[node<<1|1] = tree[node];
return ;
}
int mid = (l+r) >> 1;
update(node<<1, ql, qr, val, l, mid);
update(node<<1|1, ql, qr, val, mid+1, r);
}
void query(int node, int ql, int qr, int l, int r){
if (ql>r || qr<l) return ;
if (lazy[node]) {
tree[node] = lazy[node];
lazy[node<<1] = tree[node];
lazy[node<<1|1] = tree[node];
lazy[node] = 0;
}
if (l == r) {
if (!mark[tree[node]] && tree[node]) {
nump++;
mark[tree[node]] = true;
}
return ;
}
int mid = (l+r) >> 1;
query(node<<1, ql, qr, l, mid);
query(node<<1|1, ql, qr, mid+1, r);
}
bool fcmp(int i, int j) {
return ar[i] < ar[j];
}
|
28f5023200769c7234d77fb597bb75cc2c803760 | f0b5d296bf04ed075f44c6a18528f0c641df08a7 | /include/canard/net/ofp/v10/common/port.hpp | 0a46277f54bb7977376949e0773c124f1f37240b | [
"BSL-1.0"
] | permissive | amedama41/bulb | 7f1b181df9912f02117c9373fb1e98a5645b1f50 | 2e9fd8a8c35cfc2be2ecf5f747f83cf36ffbbdbb | refs/heads/master | 2020-05-21T20:30:02.345171 | 2017-06-02T11:03:10 | 2017-06-02T11:03:10 | 63,474,840 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,202 | hpp | port.hpp | #ifndef CANARD_NET_OFP_V10_PORT_HPP
#define CANARD_NET_OFP_V10_PORT_HPP
#include <cstdint>
#include <cstring>
#include <algorithm>
#include <boost/utility/string_ref.hpp>
#include <canard/mac_address.hpp>
#include <canard/net/ofp/detail/basic_protocol_type.hpp>
#include <canard/net/ofp/detail/decode.hpp>
#include <canard/net/ofp/detail/encode.hpp>
#include <canard/net/ofp/detail/memcmp.hpp>
#include <canard/net/ofp/v10/detail/byteorder.hpp>
#include <canard/net/ofp/v10/detail/port_adaptor.hpp>
#include <canard/net/ofp/v10/openflow.hpp>
namespace canard {
namespace net {
namespace ofp {
namespace v10 {
class port
: public v10_detail::port_adaptor<port>
, public detail::basic_protocol_type<port>
{
public:
using ofp_type = protocol::ofp_phy_port;
port(std::uint16_t const port_no
, canard::mac_address const addr
, boost::string_ref const name
, std::uint32_t const config
, std::uint32_t const state
, std::uint32_t const current_features
, std::uint32_t const advertised_features
, std::uint32_t const supported_features
, std::uint32_t const peer_advertised_features) noexcept
: port_{
port_no
, {}
, ""
, config
, state
, current_features
, advertised_features
, supported_features
, peer_advertised_features
}
{
std::memcpy(port_.hw_addr, addr.to_bytes().data(), sizeof(port_.hw_addr));
std::memcpy(
port_.name, &name[0]
, std::min(name.size(), sizeof(port_.name) - 1));
}
auto length() const noexcept
-> std::uint16_t
{
return sizeof(ofp_type);
}
auto ofp_port() const noexcept
-> ofp_type const&
{
return port_;
}
static auto from_ofp_port(ofp_type const& ofp_port) noexcept
-> port
{
return port{ofp_port};
}
private:
friend basic_protocol_type;
explicit port(ofp_type const& phy_port) noexcept
: port_(phy_port)
{
}
template <class Container>
void encode_impl(Container& container) const
{
detail::encode(container, port_);
}
template <class Iterator>
static auto decode_impl(Iterator& first, Iterator last)
-> port
{
return port{detail::decode<ofp_type>(first, last)};
}
auto equal_impl(port const& rhs) const noexcept
-> bool
{
return detail::memcmp(port_, rhs.port_);
}
auto equivalent_impl(port const& rhs) const noexcept
-> bool
{
return port_no() == rhs.port_no()
&& hardware_address() == rhs.hardware_address()
&& name() == rhs.name()
&& config() == rhs.config()
&& state() == rhs.state()
&& current_features() == rhs.current_features()
&& advertised_features() == rhs.advertised_features()
&& supported_features() == rhs.supported_features()
&& peer_advertised_features() == rhs.peer_advertised_features();
}
private:
ofp_type port_;
};
} // namespace v10
} // namespace ofp
} // namespace net
} // namespace canard
#endif // CANARD_NET_OFP_V10_PORT_HPP
|
f8a23f88e4ffb33bb9a1659e0c42313fc1614782 | e67259f518e61f2b15dda1eb767f012a5f3a6958 | /src/main/database.cpp | fe56f4aac3a36c0a6e4e4b7cce357e10b4c0721d | [
"MIT"
] | permissive | AdrianRiedl/duckdb | e0151d883d9ef2fa1b84296c57e9d5d11210e9e3 | 60c06c55973947c37fcf8feb357da802e39da3f1 | refs/heads/master | 2020-11-26T13:14:07.776404 | 2020-01-31T11:44:23 | 2020-01-31T11:44:23 | 229,081,391 | 2 | 0 | MIT | 2019-12-19T15:17:41 | 2019-12-19T15:17:40 | null | UTF-8 | C++ | false | false | 1,805 | cpp | database.cpp | #include "duckdb/main/database.hpp"
#include "duckdb/catalog/catalog.hpp"
#include "duckdb/common/file_system.hpp"
#include "duckdb/main/connection_manager.hpp"
#include "duckdb/storage/storage_manager.hpp"
#include "duckdb/transaction/transaction_manager.hpp"
using namespace duckdb;
using namespace std;
DBConfig::~DBConfig() {
}
DuckDB::DuckDB(const char *path, DBConfig *config) {
if (config) {
// user-supplied configuration
Configure(*config);
} else {
// default configuration
DBConfig config;
Configure(config);
}
if (temporary_directory.empty() && path) {
// no directory specified: use default temp path
temporary_directory = string(path) + ".tmp";
}
if (config && !config->use_temporary_directory) {
// temporary directories explicitly disabled
temporary_directory = string();
}
storage = make_unique<StorageManager>(*this, path ? string(path) : string(), access_mode == AccessMode::READ_ONLY);
catalog = make_unique<Catalog>(*storage);
transaction_manager = make_unique<TransactionManager>(*storage);
connection_manager = make_unique<ConnectionManager>();
// initialize the database
storage->Initialize();
}
DuckDB::DuckDB(const string &path, DBConfig *config) : DuckDB(path.c_str(), config) {
}
DuckDB::~DuckDB() {
}
void DuckDB::Configure(DBConfig &config) {
if (config.access_mode != AccessMode::UNDEFINED) {
access_mode = config.access_mode;
} else {
access_mode = AccessMode::READ_WRITE;
}
if (config.file_system) {
file_system = move(config.file_system);
} else {
file_system = make_unique<FileSystem>();
}
checkpoint_only = config.checkpoint_only;
checkpoint_wal_size = config.checkpoint_wal_size;
use_direct_io = config.use_direct_io;
maximum_memory = config.maximum_memory;
temporary_directory = config.temporary_directory;
}
|
b41a44f59207813346fd6252bfdb9f0b9186889f | 86a4eb14bffb0980e3936c208544613d367e936a | /HashTable.cpp | 4bad6dd30ea4643d49e463b5935912f60d6ffaff | [] | no_license | jonzivku/HashTable | 691ab2e4c47c997401316a32c7e48c5381cedfaa | bdd4b506e60e0ee83d7a857da164564939c3f395 | refs/heads/master | 2020-05-03T12:16:08.957227 | 2019-04-02T20:47:34 | 2019-04-02T20:47:34 | 178,620,894 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,420 | cpp | HashTable.cpp | // Jon Zivku, jzivku, jonzivku@me.com, HashTable.cpp, A05 Hash Table
#include <cmath>
#include <sstream>
#include <iomanip>
#include "HashTable.h"
// uses <sstream>, <iomanip>
std::string Record::str(){
std::stringstream ss;
ss << std::setw(9) << std::setfill('0') << id << " " << data;
return ss.str();
}
// uses <list>
HashTable::HashTable(int pSize) : m(pSize){
A = new std::list<Record*>[m];
}
HashTable::~HashTable(){
emptyTable();
delete [] A;
}
// uses <list>
void HashTable::emptyTable(){
for(int i = 0; i < m; i++){
for(std::list<Record*>::iterator it = A[i].begin();
it != A[i].end(); ++it){
delete *it; *it = NULL;
}
A[i].clear();
}
}
// uses <list>, Record::getId(), Record::getData(), HashTable::hash(int)
void HashTable::insert(Record *r){
if (!r)
return;
Record *s = new Record(r->getId(), r->getData());
A[hash(s->getId())].push_front(s); s = NULL;
}
// uses <list>
void HashTable::remove(int key){
int i = hash(key);
for(std::list<Record*>::iterator it = A[i].begin(); it != A[i].end(); ++it){
if((*it)->getId() == key){
delete *it; *it = NULL;
A[i].erase(it);
return;
}
}
}
// uses HashTable::find(int)
Record *HashTable::search(int key){
Record* temp = find(key);
if(temp){
//if it exists, make a copy and return it
Record *cp = new Record();
*cp = *temp;
return cp; temp = NULL;
}
else
return NULL;
}
// uses <vector>, <list>
std::vector<Record> HashTable::content(){
std::vector<Record> content;
// iterate through A
for(int i = 0; i < m; i++){
// iterate through list at A[i] and copy records to content
for(std::list<Record*>::reverse_iterator rit = A[i].rbegin();
rit != A[i].rend(); ++rit){
content.push_back(**rit); //two-star programming!
}// end of for(std::list...
}// end of for(int i...
return content;
}
// uses <list>, Record::getId()
Record* HashTable::find(int key){
int i = hash(key);
//iterate through the list at A[hash(key)]
for(std::list<Record*>::iterator it = A[i].begin(); it != A[i].end(); ++it){
if((*it)->getId() == key)
return *it;
//return the first Record* whose Id matches key
}// once the for loop is done, return NULL for no match
return NULL;
}
// uses <cmath>
int HashTable::hash(int key){
double c = (sqrt(5)-1)/2; // our constant for hashing
return floor( m * ( key*c - floor(key*c)));
}
|
799005d433cea3fb1c7a2a7b25b7d7a0c0cb3502 | 1dbddc485d32ae460945f7520d03ebc9fd3afa7d | /src/lib/access/Barrier.h | 38255b1b6310e8e4bb2e087b794bdc3dd7667844 | [
"MIT",
"LicenseRef-scancode-free-unknown"
] | permissive | hyrise/hyrise-v1 | a9e3f6b28ff74ebc670d3abce1f0ea3a5b5557f8 | d97fa0df5b9e2b9aaa78865c010e93173404086d | refs/heads/master | 2021-09-06T12:42:59.275599 | 2018-02-01T13:52:20 | 2018-02-01T13:52:20 | 8,004,429 | 8 | 6 | MIT | 2022-05-01T18:48:21 | 2013-02-04T09:26:46 | C++ | UTF-8 | C++ | false | false | 475 | h | Barrier.h | // Copyright (c) 2012 Hasso-Plattner-Institut fuer Softwaresystemtechnik GmbH. All rights reserved.
#ifndef SRC_LIB_ACCESS_BARRIER_H_
#define SRC_LIB_ACCESS_BARRIER_H_
#include "access/system/PlanOperation.h"
namespace hyrise {
namespace access {
class Barrier : public PlanOperation {
public:
void executePlanOperation();
static std::shared_ptr<PlanOperation> parse(const Json::Value& data);
const std::string vname();
};
}
}
#endif // SRC_LIB_ACCESS_BARRIER_H_
|
0a1ba7b5fc0fe51b8e6a7f9963c3f6f9c4d90bba | cee75861467875ca889e03f2781aa2893650df32 | /Greedy/minimumSubset.cpp | 4df3ee82ee42bc8fb96f8bffe8771300c6efd2b0 | [] | no_license | rutuja-patil923/Data-Structures-and-Algorithms | ad9be7494d34e62843873e2f15f288d4cfc074c7 | 9259b7ac5ab593253de163660a5e6834c4d3191b | refs/heads/master | 2023-06-04T04:31:26.143670 | 2021-06-19T06:53:59 | 2021-06-19T06:53:59 | 343,661,178 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 436 | cpp | minimumSubset.cpp | #include<bits/stdc++.h>
using namespace std;
int main()
{
int N;cin>>N;
int arr[N],sum=0;
for (int i = 0; i < N; ++i)
{
cin>>arr[i];
sum += arr[i];
}
// another way is to check if sum till current elements is greater than half of total sum
int check=0;
sort(arr,arr+N,greater<int>());
for (int i = 0; i < N; ++i)
{
/* code */
check += arr[i];
sum -= arr[i];
if(check > sum)
{
cout<<i+1;
break;
}
}
} |
a371b0fae63ff3caf4b2ca1575e500677a4bfc22 | 3f7028cc89a79582266a19acbde0d6b066a568de | /source/extensions/filters/http/rate_limit_quota/filter.cc | d789aff4f3b37fb2f2752cade3e85d4c7f412aea | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | envoyproxy/envoy | 882d3c7f316bf755889fb628bee514bb2f6f66f0 | 72f129d273fa32f49581db3abbaf4b62e3e3703c | refs/heads/main | 2023-08-31T09:20:01.278000 | 2023-08-31T08:58:36 | 2023-08-31T08:58:36 | 65,214,191 | 21,404 | 4,756 | Apache-2.0 | 2023-09-14T21:56:37 | 2016-08-08T15:07:24 | C++ | UTF-8 | C++ | false | false | 7,743 | cc | filter.cc | #include "source/extensions/filters/http/rate_limit_quota/filter.h"
#include <memory>
#include "source/extensions/filters/http/rate_limit_quota/matcher.h"
namespace Envoy {
namespace Extensions {
namespace HttpFilters {
namespace RateLimitQuota {
using ::envoy::type::v3::RateLimitStrategy;
Http::FilterHeadersStatus RateLimitQuotaFilter::decodeHeaders(Http::RequestHeaderMap& headers,
bool) {
// First, perform the request matching.
absl::StatusOr<Matcher::ActionPtr> match_result = requestMatching(headers);
if (!match_result.ok()) {
// When the request is not matched by any matchers, it is ALLOWED by default (i.e., fail-open)
// and its quota usage will not be reported to RLQS server.
// TODO(tyxia) Add stats here and other places throughout the filter (if needed).
ENVOY_LOG(debug,
"The request is not matched by any matchers: ", match_result.status().message());
return Envoy::Http::FilterHeadersStatus::Continue;
}
// Second, generate the bucket id for this request based on match action when the request matching
// succeeds.
const RateLimitOnMatchAction& match_action =
match_result.value()->getTyped<RateLimitOnMatchAction>();
auto ret = match_action.generateBucketId(*data_ptr_, factory_context_, visitor_);
if (!ret.ok()) {
// When it failed to generate the bucket id for this specific request, the request is ALLOWED by
// default (i.e., fail-open).
ENVOY_LOG(debug, "Unable to generate the bucket id: {}", ret.status().message());
return Envoy::Http::FilterHeadersStatus::Continue;
}
BucketId bucket_id_proto = ret.value();
const size_t bucket_id = MessageUtil::hash(bucket_id_proto);
if (quota_buckets_.find(bucket_id) == quota_buckets_.end()) {
// For first matched request, create a new bucket in the cache and sent the report to RLQS
// server immediately.
createNewBucket(bucket_id_proto, bucket_id);
return sendImmediateReport(bucket_id, match_action);
} else {
// Found the cached bucket entry.
// First, get the quota assignment (if exists) from the cached bucket action.
// TODO(tyxia) Implement other assignment type besides ALLOW ALL.
if (quota_buckets_[bucket_id]->bucket_action.has_quota_assignment_action()) {
auto rate_limit_strategy =
quota_buckets_[bucket_id]->bucket_action.quota_assignment_action().rate_limit_strategy();
if (rate_limit_strategy.has_blanket_rule() &&
rate_limit_strategy.blanket_rule() == envoy::type::v3::RateLimitStrategy::ALLOW_ALL) {
quota_buckets_[bucket_id]->quota_usage.num_requests_allowed += 1;
}
}
}
return Envoy::Http::FilterHeadersStatus::Continue;
}
void RateLimitQuotaFilter::createMatcher() {
RateLimitOnMatchActionContext context;
Matcher::MatchTreeFactory<Http::HttpMatchingData, RateLimitOnMatchActionContext> factory(
context, factory_context_.getServerFactoryContext(), visitor_);
if (config_->has_bucket_matchers()) {
matcher_ = factory.create(config_->bucket_matchers())();
}
}
// TODO(tyxia) Currently request matching is only performed on the request header.
absl::StatusOr<Matcher::ActionPtr>
RateLimitQuotaFilter::requestMatching(const Http::RequestHeaderMap& headers) {
// Initialize the data pointer on first use and reuse it for subsequent requests.
// This avoids creating the data object for every request, which is expensive.
if (data_ptr_ == nullptr) {
if (callbacks_ != nullptr) {
data_ptr_ = std::make_unique<Http::Matching::HttpMatchingDataImpl>(callbacks_->streamInfo());
} else {
return absl::InternalError("Filter callback has not been initialized successfully yet.");
}
}
if (matcher_ == nullptr) {
return absl::InternalError("Matcher tree has not been initialized yet.");
} else {
// Populate the request header.
if (!headers.empty()) {
data_ptr_->onRequestHeaders(headers);
}
// Perform the matching.
auto match_result = Matcher::evaluateMatch<Http::HttpMatchingData>(*matcher_, *data_ptr_);
if (match_result.match_state_ == Matcher::MatchState::MatchComplete) {
if (match_result.result_) {
// Return the matched result for `on_match` case.
return match_result.result_();
} else {
return absl::NotFoundError("Matching completed but no match result was found.");
}
} else {
// The returned state from `evaluateMatch` function is `MatchState::UnableToMatch` here.
return absl::InternalError("Unable to match due to the required data not being available.");
}
}
}
void RateLimitQuotaFilter::onQuotaResponse(RateLimitQuotaResponse&) {
if (!initiating_call_) {
callbacks_->continueDecoding();
}
}
void RateLimitQuotaFilter::onDestroy() {
// TODO(tyxia) TLS resource are not cleaned here.
}
void RateLimitQuotaFilter::createNewBucket(const BucketId& bucket_id, size_t id) {
// The first matched request doesn't have quota assignment from the RLQS server yet, so the
// action is performed based on pre-configured strategy from no assignment behavior config.
// TODO(tyxia) Check no assignment logic for new bucket (i.e., first matched request). Default is
// allow all.
QuotaUsage quota_usage;
quota_usage.num_requests_allowed = 1;
quota_usage.num_requests_denied = 0;
quota_usage.last_report = std::chrono::duration_cast<std::chrono::nanoseconds>(
time_source_.monotonicTime().time_since_epoch());
// Create new bucket and store it into quota cache.
std::unique_ptr<Bucket> new_bucket = std::make_unique<Bucket>();
new_bucket->bucket_id = bucket_id;
new_bucket->quota_usage = quota_usage;
quota_buckets_[id] = std::move(new_bucket);
}
Http::FilterHeadersStatus
RateLimitQuotaFilter::sendImmediateReport(const size_t bucket_id,
const RateLimitOnMatchAction& match_action) {
const auto& bucket_settings = match_action.bucketSettings();
// Create the gRPC client if it has not been created.
if (client_.rate_limit_client == nullptr) {
client_.rate_limit_client = createRateLimitClient(factory_context_, config_->rlqs_server(),
this, quota_buckets_, config_->domain());
} else {
// Callback has been reset to nullptr when filter was destroyed last time.
// Reset it here when new filter has been created.
client_.rate_limit_client->setCallback(this);
}
// It can not be nullptr based on current implementation.
ASSERT(client_.rate_limit_client != nullptr);
// Start the streaming on the first request.
auto status = client_.rate_limit_client->startStream(callbacks_->streamInfo());
if (!status.ok()) {
ENVOY_LOG(error, "Failed to start the gRPC stream: ", status.message());
return Envoy::Http::FilterHeadersStatus::Continue;
}
initiating_call_ = true;
// Send the usage report to RLQS server immediately on the first time when the request is
// matched.
client_.rate_limit_client->sendUsageReport(bucket_id);
ASSERT(client_.send_reports_timer != nullptr);
// Set the reporting interval and enable the timer.
const int64_t reporting_interval = PROTOBUF_GET_MS_REQUIRED(bucket_settings, reporting_interval);
client_.send_reports_timer->enableTimer(std::chrono::milliseconds(reporting_interval));
initiating_call_ = false;
// TODO(tyxia) Revisit later.
// Stop the iteration for headers as well as data and trailers for the current filter and the
// filters following.
return Http::FilterHeadersStatus::StopAllIterationAndWatermark;
}
} // namespace RateLimitQuota
} // namespace HttpFilters
} // namespace Extensions
} // namespace Envoy
|
efa6b635c5373d07887af42c7bc925377bac798b | 48a761c24be1181b7506f656ad4ac734944dc24e | /Appointment_System/src/model/tcpConnection.cpp | 5c698bbbe1c4d5af1a9c931f3d078018d71070c0 | [] | no_license | hchen106/Appointment_System | 9fb48f99da2c9eb5f55f7624b4f51d35ec17418d | 1b9984bce4896a1965256e1b4af465454e24f78b | refs/heads/master | 2023-02-09T23:21:53.556304 | 2021-01-05T04:32:25 | 2021-01-05T04:32:25 | 281,277,620 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 462 | cpp | tcpConnection.cpp | #include "tcpConnection.h"
tcpConnection::tcpConnection(boost::asio::io_service& io_service, boost::asio::ssl::context& context) : socket_(io_service), tcp_socket(std::move(socket_),context) {
}
tcpConnection::pointer tcpConnection::create(boost::asio::io_service& io_service, boost::asio::ssl::context& context_) {
return tcpConnection::pointer(new tcpConnection(io_service,context_));
}
ip::tcp::socket& tcpConnection::socket() {
return socket_;
} |
8fc44656f79e29ef449ce673535cc2d4229f4f35 | a117d85fbc7de4d1416b6c5d903c1ca7d1850f07 | /codeEval/dna.cpp | 6281b15505da2bde3938245599b91064fb7501d9 | [] | no_license | moutard/learn | 2a10d88a4d7a61af96915d75d4790858eb405c6c | 5ee94b09a2ca2b30eacedd51a2885c29b454668c | refs/heads/master | 2021-05-01T00:20:03.925763 | 2014-06-01T15:25:56 | 2014-06-01T15:25:56 | 9,283,361 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,000 | cpp | dna.cpp | #include <string>
#include <vector>
#include <map>
#include <algorithm> // std::sort
#include <iostream>
#include <sstream>
#include <fstream>
using namespace std;
unsigned int min(unsigned int a, unsigned int b, unsigned int c) {
unsigned int min;
if (a < b) {
min = a;
} else {
min = b;
}
if (c < min) {
return c;
} else {
return min;
}
};
int levenshteinDistance(const std::string & s, const std::string & t) {
// Degenerate Cases.
if (s.compare(t)==0) { return 0;}
unsigned int iSLength = s.size();
unsigned int iTLength = t.size();
if (iSLength == 0) {return iTLength;}
if (iTLength == 0) {return iSLength;}
// Create the two vectors (corresponds to the previous and current line of the matrix)
unsigned int v0[iTLength + 1];
unsigned int v1[iTLength + 1];
// Initialize each vector.
for (unsigned int i = 0; i < iTLength + 1; ++i) {
v0[i] = i;
}
for (unsigned int i = 0; i < iSLength; ++i) {
// Calculate v1 (the current row distance)
v1[0] = i + 1;
// Use the formulat to fill in the rest of the row.
for (unsigned int j = 0; j < iTLength; ++j) {
unsigned int cost = (s[i] == t[j]) ? 0 : 1;
v1[j+1] = min(v1[j] + 1, v0[j+1] + 1, v0[j] + cost);
}
// copy v1 (current row) to v0;
for (unsigned int k = 0; k < iTLength + 1; ++k) {
v0[k] = v1[k];
}
}
return v1[iTLength];
};
unsigned int search(std::string segment, std::string dna, int max_distance) {
std::map<int, std::vector<std::string> > seq;
unsigned int counter = 0;
unsigned int segmentLength = segment.size();
unsigned int dnaLength = dna.size();
std::string substring;
for (unsigned int i = 0; i < (dnaLength - segmentLength + 1); ++i) {
substring = dna.substr(i, segmentLength);
int lev = levenshteinDistance(segment, substring);
if (lev <= max_distance) {
counter++;
seq[lev].push_back(substring);
}
}
std::map<int, std::vector<std::string> >::iterator it;
if (seq.empty()) {
std::cout << "No match" << endl;
} else {
int needSpace = 0;
for (it = seq.begin(); it != seq.end(); ++it) {
std::vector<std::string>::iterator it2;
std::sort (it->second.begin(), it->second.end());
for (it2 = it->second.begin(); it2 != it->second.end(); ++it2) {
if (!needSpace) {
std::cout << *it2;
needSpace = 1;
} else {
std::cout << " " << *it2;
}
}
}
std::cout << endl;
}
return counter;
}
int main(int argc, char *argv[]) {
ifstream oFile;
oFile.open(argv[1], ios::in);
if (oFile.is_open()) {
string segment;
string dna;
string max_distance;
char * tmp;
std::string line;
while(getline(oFile, line)) {
std::stringstream ss(line);
std::getline(ss, segment, ' ');
std::getline(ss, max_distance, ' ');
std::getline(ss, dna, ' ');
search(segment, dna, atoi(max_distance.c_str()));
}
oFile.close();
}
}
|
8254903b42a33d2a7e05522992f483c108e11645 | a3d6556180e74af7b555f8d47d3fea55b94bcbda | /chrome/installer/util/delete_after_reboot_helper.h | 50cb87ba0616ef47fabd1841364a05a2d3e869f9 | [
"BSD-3-Clause"
] | permissive | chromium/chromium | aaa9eda10115b50b0616d2f1aed5ef35d1d779d6 | a401d6cf4f7bf0e2d2e964c512ebb923c3d8832c | refs/heads/main | 2023-08-24T00:35:12.585945 | 2023-08-23T22:01:11 | 2023-08-23T22:01:11 | 120,360,765 | 17,408 | 7,102 | BSD-3-Clause | 2023-09-10T23:44:27 | 2018-02-05T20:55:32 | null | UTF-8 | C++ | false | false | 3,349 | h | delete_after_reboot_helper.h | // Copyright 2009 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
// This file declares helper methods used to schedule files for deletion
// on next reboot.
#ifndef CHROME_INSTALLER_UTIL_DELETE_AFTER_REBOOT_HELPER_H_
#define CHROME_INSTALLER_UTIL_DELETE_AFTER_REBOOT_HELPER_H_
#include <string>
#include <vector>
#include <windows.h>
#include <stddef.h>
namespace base {
class FilePath;
}
// Used by the unit tests.
extern const wchar_t kSessionManagerKey[];
extern const wchar_t kPendingFileRenameOps[];
typedef std::pair<std::wstring, std::wstring> PendingMove;
// Attempts to schedule only the item at path for deletion.
bool ScheduleFileSystemEntityForDeletion(const base::FilePath& path);
// Attempts to recursively schedule the directory for deletion.
bool ScheduleDirectoryForDeletion(const base::FilePath& dir_name);
// Removes all pending moves that are registered for |directory| and all
// elements contained in |directory|.
bool RemoveFromMovesPendingReboot(const base::FilePath& directory);
// Retrieves the list of pending renames from the registry and returns a vector
// containing pairs of strings that represent the operations. If the list
// contains only deletes then every other element will be an empty string
// as per http://msdn.microsoft.com/en-us/library/aa365240(VS.85).aspx.
HRESULT GetPendingMovesValue(std::vector<PendingMove>* pending_moves);
// This returns true if |short_form_needle| is contained in |reg_path| where
// |short_form_needle| is a file system path that has been shortened by
// GetShortPathName and |reg_path| is a path stored in the
// PendingFileRenameOperations key.
bool MatchPendingDeletePath(const base::FilePath& short_form_needle,
const base::FilePath& reg_path);
// Converts the strings found in |buffer| to a list of PendingMoves that is
// returned in |value|.
// |buffer| points to a series of pairs of null-terminated wchar_t strings
// followed by a terminating null character.
// |byte_count| is the length of |buffer| in bytes.
// |value| is a pointer to an empty vector of PendingMoves (string pairs).
// On success, this vector contains all of the string pairs extracted from
// |buffer|.
// Returns S_OK on success, E_INVALIDARG if buffer does not meet the above
// specification.
HRESULT MultiSZBytesToStringArray(const char* buffer,
size_t byte_count,
std::vector<PendingMove>* value);
// The inverse of MultiSZBytesToStringArray, this function converts a list
// of string pairs into a byte array format suitable for writing to the
// kPendingFileRenameOps registry value. It concatenates the strings and
// appends an additional terminating null character.
void StringArrayToMultiSZBytes(const std::vector<PendingMove>& strings,
std::vector<char>* buffer);
// A helper function for the win32 GetShortPathName that more conveniently
// returns a FilePath. Note that if |path| is not present on the file system
// then GetShortPathName will return |path| unchanged, unlike the win32
// GetShortPathName which will return an error.
base::FilePath GetShortPathName(const base::FilePath& path);
#endif // CHROME_INSTALLER_UTIL_DELETE_AFTER_REBOOT_HELPER_H_
|
4f234e2717cf44e3be101aa3627cf76a4da4d2e2 | 9be246df43e02fba30ee2595c8cec14ac2b355d1 | /utils/tfstats/weaponawards.h | d22bef391b2f98d07b40c01c907228bce460b2f2 | [] | no_license | Clepoy3/LeakNet | 6bf4c5d5535b3824a350f32352f457d8be87d609 | 8866efcb9b0bf9290b80f7263e2ce2074302640a | refs/heads/master | 2020-05-30T04:53:22.193725 | 2019-04-12T16:06:26 | 2019-04-12T16:06:26 | 189,544,338 | 18 | 5 | null | 2019-05-31T06:59:39 | 2019-05-31T06:59:39 | null | UTF-8 | C++ | false | false | 5,761 | h | weaponawards.h | //=========== (C) Copyright 1999 Valve, L.L.C. All rights reserved. ===========
//
// The copyright to the contents herein is the property of Valve, L.L.C.
// The contents may be used and/or copied only with the written permission of
// Valve, L.L.C., or in accordance with the terms and conditions stipulated in
// the agreement/contract under which the contents have been supplied.
//
// Purpose: Interface of the CWeaponAward class, and its subclasses
//
// $Workfile: $
// $Date: $
//
//------------------------------------------------------------------------------------------------------
// $Log: $
//
// $NoKeywords: $
//=============================================================================
#ifndef WEAPONAWARDS_H
#define WEAPONAWARDS_H
#ifdef WIN32
#pragma once
#endif
#include "Award.h"
//------------------------------------------------------------------------------------------------------
// Purpose: CWeaponAward is the superclass for any award that is based simply
// on number of kills with a specific weapon.
//------------------------------------------------------------------------------------------------------
class CWeaponAward: public CAward
{
protected:
map<PID,int> accum;
char* killtype;
public:
CWeaponAward(char* awardname, char* killname):CAward(awardname),killtype(killname){}
void getWinner();
};
//------------------------------------------------------------------------------------------------------
// Purpose: CFlamethrowerAward is an award given to the player who gets the
// most kills with "flames"
//------------------------------------------------------------------------------------------------------
class CFlamethrowerAward: public CWeaponAward
{
protected:
void noWinner(CHTMLFile& html);
void extendedinfo(CHTMLFile& html);
public:
explicit CFlamethrowerAward():CWeaponAward("Blaze of Glory","flames"){}
};
//------------------------------------------------------------------------------------------------------
// Purpose: CAssaultCannonAward is an award given to the player who gets the
// most kills with "ac" (the assault cannon)
//------------------------------------------------------------------------------------------------------
class CAssaultCannonAward: public CWeaponAward
{
protected:
void noWinner(CHTMLFile& html);
void extendedinfo(CHTMLFile& html);
public:
explicit CAssaultCannonAward():CWeaponAward("Swiss Cheese","ac"){}
};
//------------------------------------------------------------------------------------------------------
// Purpose: CKnifeAward is an award given to the player who gets the most kills
// with the "knife"
//------------------------------------------------------------------------------------------------------
class CKnifeAward: public CWeaponAward
{
protected:
void noWinner(CHTMLFile& html);
void extendedinfo(CHTMLFile& html);
public:
explicit CKnifeAward():CWeaponAward("Assassin","knife"){}
};
//------------------------------------------------------------------------------------------------------
// Purpose: CRocketryAward is an award given to the player who gets the most kills
// with "rocket"s.
//------------------------------------------------------------------------------------------------------
class CRocketryAward: public CWeaponAward
{
protected:
void noWinner(CHTMLFile& html);
void extendedinfo(CHTMLFile& html);
public:
explicit CRocketryAward():CWeaponAward("Rocketry","rocket"){}
};
//------------------------------------------------------------------------------------------------------
// Purpose: CGrenadierAward is an award given to the player who gets the most
// kills with "gl_grenade"s
//------------------------------------------------------------------------------------------------------
class CGrenadierAward: public CWeaponAward
{
protected:
void noWinner(CHTMLFile& html);
void extendedinfo(CHTMLFile& html);
public:
explicit CGrenadierAward():CWeaponAward("Grenadier","gl_grenade"){}
};
//------------------------------------------------------------------------------------------------------
// Purpose: CDemolitionsAward is an award given to the player who kills the most
// people with "detpack"s.
//------------------------------------------------------------------------------------------------------
class CDemolitionsAward: public CWeaponAward
{
protected:
void noWinner(CHTMLFile& html);
void extendedinfo(CHTMLFile& html);
public:
explicit CDemolitionsAward():CWeaponAward("Demolitions","detpack"){}
};
//------------------------------------------------------------------------------------------------------
// Purpose: CBiologicalWarfareAward is given to the player who kills the most
// people with "infection"s
//------------------------------------------------------------------------------------------------------
class CBiologicalWarfareAward: public CWeaponAward
{
protected:
void noWinner(CHTMLFile& html);
void extendedinfo(CHTMLFile& html);
public:
CBiologicalWarfareAward():CWeaponAward("Biological Warfare","infection"){}
};
//------------------------------------------------------------------------------------------------------
// Purpose: CBestSentryAward is given to the player who kills the most people
// with sentry guns that he/she created ("sentrygun")
//------------------------------------------------------------------------------------------------------
class CBestSentryAward: public CWeaponAward
{
protected:
void noWinner(CHTMLFile& html);
void extendedinfo(CHTMLFile& html);
public:
CBestSentryAward():CWeaponAward("Best Sentry Placement","sentrygun"){}
};
#endif // WEAPONAWARDS_H
|
9dcf540dcdf8303715bad6845ef2527a88c3ac70 | 471e7253cc79f86d47c1e53b493131c748364d45 | /GasRemote/CE/winceCompass/compass.cpp | c4f7657efb76f219d2ba4c3716cf6ff7bbd3fd9e | [] | no_license | Quenii/adcevm | 9ed6dff30eac0dd12ecbf08ff19e555aff25c0ca | b15ad0dd33a64f26fc89dbe9c595f80abbf99230 | refs/heads/master | 2016-09-06T11:00:06.719515 | 2014-12-26T08:12:31 | 2014-12-26T08:12:31 | 34,307,888 | 2 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 3,778 | cpp | compass.cpp | #include "compass.h"
// 5 + 2 + 3 + 1
#define MSGLEN 11
Compass::Compass()
: rfPower(0),
: hostID(0)
{
buffer.RemoveAll();
}
Compass * Compass::instance(QextSerialPort* term)
{
static Compass _instance;
if (term != NULL)
_instance.term = term;
return &_instance;
}
bool Compass::getMessage(CByteArray& msg, const QByteArray& hdr)
{
int len = MSGLEN;
if (term->bytesAvailable()) {
buffer += term->readAll();
qDebug() << QString("buffer Length after reading %1").arg(buffer.size());
}
if(buffer.size() > MSGLEN)
{
int j = 0;
if ((j = buffer.indexOf('$', j)) >= 0) {
buffer = buffer.mid(j);
}else{
buffer.clear();
return false;
}
j = buffer.indexOf(hdr);
if (j >= 0 && (buffer.size()-j) > 7) //long enough to have length info
{
len = buffer[j+5]*256 + buffer[j+6];
if ((buffer.size()-j) >= len) //complete msg
{
msg = buffer.mid(j, len);
buffer = buffer.left(j) + buffer.right(buffer.size()-j-len);
qDebug() << QString("Got Message at length %1, msg = %2").arg(len).arg(QString(msg));
return true;
}
}
}
if (buffer.size() > 16384)
buffer.clear();
return false;
}
bool Compass::getLocation()
{
COMPASSCMD cmd;
cmd.cmdword = "$DWSQ";
cmd.params[0] = 0x04;
for(int i=0; i<10; ++i)
{
cmd.params[i+1] = 0;
}
sendCommand(cmd);
return true;
}
bool Compass::getID(uint& id)
{
COMPASSCMD cmd;
cmd.cmdword = "$ICJC";
cmd.params[0] = 0;
sendCommand(cmd);
sleep(1);
QByteArray msg;
if (getMessage(msg, QByteArray("$ICXX")))
{
unsigned char *t = (unsigned char *)&id;
for(int i=0; i<3; ++i)
{
t[2-i] = msg[i+7];
}
hostID = id;
qDebug() << QString("HostID: %1").arg(hostID);
return true;
}
return false;
}
void Compass::sendCommand(COMPASSCMD &cmd)
{
cmd.addr = hostID;
cmd.len = cmd.params.size() + MSGLEN;
QByteArray buf;
buf = cmd.cmdword;
buf[5] = cmd.len >> 8;
buf[6] = cmd.len % 255;
for(int i=0; i<3; ++i)
{
buf[i+7] = cmd.addr >> (2-i)*8;
unsigned char u = buf[buf.size()-1];
}
buf.append(cmd.params);
unsigned char parity = 0;
for(int i=0; i<buf.size(); ++i)
{
parity = parity ^ buf[i];
}
buf[buf.size()] = parity;
term->write(buf);
qDebug() << QString("Sending Cmd: %1, length: %2").arg(QString(buf)).arg(buf.size());
}
int Compass::getRFPower()
{
COMPASSCMD cmd;
cmd.cmdword = "$GLJC";
cmd.params[0] = 0;
sendCommand(cmd);
QByteArray msg;
if (getMessage(msg, QByteArray("$GLZK")))
{
unsigned char sum = 0;
for(int i=0; i<rfPower.size(); ++i)
{
rfPower[i] = msg[i+10];
unsigned char u = rfPower[i];
sum += rfPower[i];
qDebug() << QString("Power of Beam %1 = %2").arg(i).arg(u);
}
if (sum > 4)
return 1;
else
return 0;
}
return -1;
}
bool Compass::sendMessage(const uint &adr, QByteArray& msg)
{
COMPASSCMD cmd;
cmd.cmdword = "$TXSQ";
cmd.params[0] = 0x46; //
cmd.params[cmd.params.size()] = (adr >> 16) & 0xFF;
cmd.params[cmd.params.size()] = (adr >> 8) & 0xFF;
cmd.params[cmd.params.size()] = (adr >> 0) & 0xFF;
cmd.params[cmd.params.size()] = msg.size() * 8 / 256;
cmd.params[cmd.params.size()] = msg.size() * 8 % 256;
cmd.params[cmd.params.size()] = 0; //answer or not
cmd.params.append(msg);
sendCommand(cmd);
return true;
}
|
5eef94590d8d07455f1cd19d50f076351b125873 | d70507b1272a6280b99bbc54e211b32c07faddb4 | /VideoDesktop/finddesktop.cpp | 87cb16862d26ca87ce9086417ee8b8b5d82ed3e4 | [
"MIT"
] | permissive | dongyancong/VideoWallpaper | 3a4126c9dac85ad56e041129f488a85f666b509d | 1085627cecc101851ee725f8dfb12bd6f3ee1676 | refs/heads/master | 2022-01-06T13:54:05.312571 | 2018-09-15T12:07:53 | 2018-09-15T12:07:53 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,044 | cpp | finddesktop.cpp | #include"finddesktop.h"
HWND WorkerW=NULL;
HWND findDesktopIconWnd()
{
HWND hWorkerW = NULL;//WorkerW的句柄
HWND hDefView = NULL;//SHELLDLL_DefView的句柄
//找到WorkerW类的窗口
hWorkerW = FindWindowEx(NULL, NULL, L"WorkerW", NULL);
//通过遍历找到包含SHELLDLL_DefView的WorkerW
while ((!hDefView) && hWorkerW)
{
hDefView = FindWindowEx(hWorkerW, NULL, L"SHELLDLL_DefView", NULL);
WorkerW=hWorkerW;//得到WorkerW
hWorkerW = FindWindowEx(NULL, hWorkerW, L"WorkerW", NULL);
}
//隐藏窗口,不让mainwindow被挡住
ShowWindow(hWorkerW,0);
return FindWindow(L"Progman",NULL);
}
void SendMessageToDesktop()
{
PDWORD_PTR result = NULL;
//发送消息,召唤WorkerW
//参考:https://www.codeproject.com/articles/856020/draw-behind-desktop-icons-in-windows
SendMessageTimeout(FindWindow(L"Progman",NULL), 0x52c, 0, 0, SMTO_NORMAL, 1000, result);
}
HWND GetWorkerW()
{
findDesktopIconWnd();
return WorkerW;//得到WorkerW
}
|
74c0aeaaa69c2908bd15d6c5977f4148ac3e629c | edf4f46f7b473ce341ba292f84e3d1760218ebd1 | /src/inet/UDPEndPoint.cpp | d741842da2fa2abe843ac16fd7a72db666d1d899 | [
"LicenseRef-scancode-proprietary-license",
"Apache-2.0"
] | permissive | openweave/openweave-core | 7e7e6f6c089e2e8015a8281f74fbdcaf4aca5d2a | e3c8ca3d416a2e1687d6f5b7cec0b7d0bf1e590e | refs/heads/master | 2022-11-01T17:21:59.964473 | 2022-08-10T16:36:19 | 2022-08-10T16:36:19 | 101,915,019 | 263 | 125 | Apache-2.0 | 2022-10-17T18:48:30 | 2017-08-30T18:22:10 | C++ | UTF-8 | C++ | false | false | 29,077 | cpp | UDPEndPoint.cpp | /*
*
* Copyright (c) 2018 Google LLC.
* Copyright (c) 2013-2018 Nest Labs, Inc.
* All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* @file
* This file implements the <tt>nl::Inet::UDPEndPoint</tt>
* class, where the Nest Inet Layer encapsulates methods for
* interacting with UDP transport endpoints (SOCK_DGRAM sockets
* on Linux and BSD-derived systems) or LwIP UDP protocol
* control blocks, as the system is configured accordingly.
*
*/
#define __APPLE_USE_RFC_3542
#include <string.h>
#include <InetLayer/UDPEndPoint.h>
#include <InetLayer/InetLayer.h>
#include <InetLayer/InetFaultInjection.h>
#include <SystemLayer/SystemFaultInjection.h>
#include <Weave/Support/CodeUtils.h>
#include <Weave/Support/logging/WeaveLogging.h>
#if WEAVE_SYSTEM_CONFIG_USE_LWIP
#include <lwip/udp.h>
#include <lwip/tcpip.h>
#include <lwip/ip.h>
#endif // WEAVE_SYSTEM_CONFIG_USE_LWIP
#if WEAVE_SYSTEM_CONFIG_USE_SOCKETS
#include <poll.h>
#if HAVE_SYS_SOCKET_H
#include <sys/socket.h>
#endif // HAVE_SYS_SOCKET_H
#include <errno.h>
#include <unistd.h>
#include <net/if.h>
#include <netinet/in.h>
#endif // WEAVE_SYSTEM_CONFIG_USE_SOCKETS
#include "arpa-inet-compatibility.h"
// SOCK_CLOEXEC not defined on all platforms, e.g. iOS/MacOS:
#ifdef SOCK_CLOEXEC
#define SOCK_FLAGS SOCK_CLOEXEC
#else
#define SOCK_FLAGS 0
#endif
namespace nl {
namespace Inet {
using Weave::System::PacketBuffer;
Weave::System::ObjectPool<UDPEndPoint, INET_CONFIG_NUM_UDP_ENDPOINTS> UDPEndPoint::sPool;
#if WEAVE_SYSTEM_CONFIG_USE_LWIP
/*
* Note that for LwIP InterfaceId is already defined to be 'struct
* netif'; consequently, some of the checking performed here could
* conceivably be optimized out and the HAVE_LWIP_UDP_BIND_NETIF case
* could simply be:
*
* udp_bind_netif(aUDP, intfId);
*
*/
static INET_ERROR LwIPBindInterface(struct udp_pcb *aUDP, InterfaceId intfId)
{
INET_ERROR res = INET_NO_ERROR;
#if HAVE_LWIP_UDP_BIND_NETIF
if (!IsInterfaceIdPresent(intfId))
udp_bind_netif(aUDP, NULL);
else
{
struct netif *netifp = IPEndPointBasis::FindNetifFromInterfaceId(intfId);
if (netifp == NULL)
res = INET_ERROR_UNKNOWN_INTERFACE;
else
udp_bind_netif(aUDP, netifp);
}
#else
if (!IsInterfaceIdPresent(intfId))
aUDP->intf_filter = NULL;
else
{
struct netif *netifp = IPEndPointBasis::FindNetifFromInterfaceId(intfId);
if (netifp == NULL)
res = INET_ERROR_UNKNOWN_INTERFACE;
else
aUDP->intf_filter = netifp;
}
#endif // HAVE_LWIP_UDP_BIND_NETIF
return res;
}
#endif // WEAVE_SYSTEM_CONFIG_USE_LWIP
/**
* @brief Bind the endpoint to an interface IP address.
*
* @param[in] addrType the protocol version of the IP address
* @param[in] addr the IP address (must be an interface address)
* @param[in] port the UDP port
* @param[in] intfId an optional network interface indicator
*
* @retval INET_NO_ERROR success: endpoint bound to address
* @retval INET_ERROR_INCORRECT_STATE endpoint has been bound previously
* @retval INET_NO_MEMORY insufficient memory for endpoint
*
* @retval INET_ERROR_UNKNOWN_INTERFACE
* On some platforms, the optionally specified interface is not
* present.
*
* @retval INET_ERROR_WRONG_PROTOCOL_TYPE
* \c addrType does not match \c IPVer.
*
* @retval INET_ERROR_WRONG_ADDRESS_TYPE
* \c addrType is \c kIPAddressType_Any, or the type of \c addr is not
* equal to \c addrType.
*
* @retval other another system or platform error
*
* @details
* Binds the endpoint to the specified network interface IP address.
*
* On LwIP, this method must not be called with the LwIP stack lock
* already acquired.
*/
INET_ERROR UDPEndPoint::Bind(IPAddressType addrType, IPAddress addr, uint16_t port, InterfaceId intfId)
{
INET_ERROR res = INET_NO_ERROR;
if (mState != kState_Ready && mState != kState_Bound)
{
res = INET_ERROR_INCORRECT_STATE;
goto exit;
}
if ((addr != IPAddress::Any) && (addr.Type() != kIPAddressType_Any) && (addr.Type() != addrType))
{
res = INET_ERROR_WRONG_ADDRESS_TYPE;
goto exit;
}
#if WEAVE_SYSTEM_CONFIG_USE_LWIP
// Lock LwIP stack
LOCK_TCPIP_CORE();
// Make sure we have the appropriate type of PCB.
res = GetPCB(addrType);
// Bind the PCB to the specified address/port.
if (res == INET_NO_ERROR)
{
#if LWIP_VERSION_MAJOR > 1 || LWIP_VERSION_MINOR >= 5
ip_addr_t ipAddr = addr.ToLwIPAddr();
#if INET_CONFIG_ENABLE_IPV4
lwip_ip_addr_type lType = IPAddress::ToLwIPAddrType(addrType);
IP_SET_TYPE_VAL(ipAddr, lType);
#endif // INET_CONFIG_ENABLE_IPV4
res = Weave::System::MapErrorLwIP(udp_bind(mUDP, &ipAddr, port));
#else // LWIP_VERSION_MAJOR <= 1 && LWIP_VERSION_MINOR < 5
if (addrType == kIPAddressType_IPv6)
{
ip6_addr_t ipv6Addr = addr.ToIPv6();
res = Weave::System::MapErrorLwIP(udp_bind_ip6(mUDP, &ipv6Addr, port));
}
#if INET_CONFIG_ENABLE_IPV4
else if (addrType == kIPAddressType_IPv4)
{
ip4_addr_t ipv4Addr = addr.ToIPv4();
res = Weave::System::MapErrorLwIP(udp_bind(mUDP, &ipv4Addr, port));
}
#endif // INET_CONFIG_ENABLE_IPV4
else
res = INET_ERROR_WRONG_ADDRESS_TYPE;
#endif // LWIP_VERSION_MAJOR <= 1 || LWIP_VERSION_MINOR >= 5
}
if (res == INET_NO_ERROR)
{
res = LwIPBindInterface(mUDP, intfId);
}
// Unlock LwIP stack
UNLOCK_TCPIP_CORE();
SuccessOrExit(res);
#endif // WEAVE_SYSTEM_CONFIG_USE_LWIP
#if WEAVE_SYSTEM_CONFIG_USE_SOCKETS
// Make sure we have the appropriate type of socket.
res = GetSocket(addrType);
SuccessOrExit(res);
res = IPEndPointBasis::Bind(addrType, addr, port, intfId);
SuccessOrExit(res);
mBoundPort = port;
mBoundIntfId = intfId;
// If an ephemeral port was requested, retrieve the actual bound port.
if (port == 0)
{
union
{
struct sockaddr any;
struct sockaddr_in in;
struct sockaddr_in6 in6;
} boundAddr;
socklen_t boundAddrLen = sizeof(boundAddr);
if (getsockname(mSocket, &boundAddr.any, &boundAddrLen) == 0)
{
if (boundAddr.any.sa_family == AF_INET)
{
mBoundPort = ntohs(boundAddr.in.sin_port);
}
else if (boundAddr.any.sa_family == AF_INET6)
{
mBoundPort = ntohs(boundAddr.in6.sin6_port);
}
}
}
#endif // WEAVE_SYSTEM_CONFIG_USE_SOCKETS
if (res == INET_NO_ERROR)
{
mState = kState_Bound;
}
exit:
return res;
}
/**
* @brief Prepare the endpoint to receive UDP messages.
*
* @retval INET_NO_ERROR success: endpoint ready to receive messages.
* @retval INET_ERROR_INCORRECT_STATE endpoint is already listening.
*
* @details
* If \c State is already \c kState_Listening, then no operation is
* performed, otherwise the \c mState is set to \c kState_Listening and
* the endpoint is prepared to received UDP messages, according to the
* semantics of the platform.
*
* On LwIP, this method must not be called with the LwIP stack lock
* already acquired
*/
INET_ERROR UDPEndPoint::Listen(void)
{
INET_ERROR res = INET_NO_ERROR;
#if WEAVE_SYSTEM_CONFIG_USE_SOCKETS
Weave::System::Layer& lSystemLayer = SystemLayer();
#endif // WEAVE_SYSTEM_CONFIG_USE_SOCKETS
if (mState == kState_Listening)
{
res = INET_NO_ERROR;
goto exit;
}
if (mState != kState_Bound)
{
res = INET_ERROR_INCORRECT_STATE;
goto exit;
}
#if WEAVE_SYSTEM_CONFIG_USE_LWIP
// Lock LwIP stack
LOCK_TCPIP_CORE();
#if LWIP_VERSION_MAJOR > 1 || LWIP_VERSION_MINOR >= 5
udp_recv(mUDP, LwIPReceiveUDPMessage, this);
#else // LWIP_VERSION_MAJOR <= 1 && LWIP_VERSION_MINOR < 5
if (PCB_ISIPV6(mUDP))
udp_recv_ip6(mUDP, LwIPReceiveUDPMessage, this);
else
udp_recv(mUDP, LwIPReceiveUDPMessage, this);
#endif // LWIP_VERSION_MAJOR <= 1 || LWIP_VERSION_MINOR >= 5
// Unlock LwIP stack
UNLOCK_TCPIP_CORE();
#endif // WEAVE_SYSTEM_CONFIG_USE_LWIP
#if WEAVE_SYSTEM_CONFIG_USE_SOCKETS
// Wake the thread calling select so that it starts selecting on the new socket.
lSystemLayer.WakeSelect();
#endif // WEAVE_SYSTEM_CONFIG_USE_SOCKETS
if (res == INET_NO_ERROR)
{
mState = kState_Listening;
}
exit:
return res;
}
/**
* @brief Close the endpoint.
*
* @details
* If <tt>mState != kState_Closed</tt>, then closes the endpoint, removing
* it from the set of endpoints eligible for communication events.
*
* On LwIP systems, this method must not be called with the LwIP stack
* lock already acquired.
*/
void UDPEndPoint::Close(void)
{
if (mState != kState_Closed)
{
#if WEAVE_SYSTEM_CONFIG_USE_LWIP
// Lock LwIP stack
LOCK_TCPIP_CORE();
// Since UDP PCB is released synchronously here, but UDP endpoint itself might have to wait
// for destruction asynchronously, there could be more allocated UDP endpoints than UDP PCBs.
if (mUDP != NULL)
{
udp_remove(mUDP);
mUDP = NULL;
mLwIPEndPointType = kLwIPEndPointType_Unknown;
}
// Unlock LwIP stack
UNLOCK_TCPIP_CORE();
#endif // WEAVE_SYSTEM_CONFIG_USE_LWIP
#if WEAVE_SYSTEM_CONFIG_USE_SOCKETS
if (mSocket != INET_INVALID_SOCKET_FD)
{
Weave::System::Layer& lSystemLayer = SystemLayer();
// Wake the thread calling select so that it recognizes the socket is closed.
lSystemLayer.WakeSelect();
close(mSocket);
mSocket = INET_INVALID_SOCKET_FD;
}
// Clear any results from select() that indicate pending I/O for the socket.
mPendingIO.Clear();
#endif // WEAVE_SYSTEM_CONFIG_USE_SOCKETS
mState = kState_Closed;
}
}
/**
* @brief Close the endpoint and recycle its memory.
*
* @details
* Invokes the \c Close method, then invokes the
* <tt>InetLayerBasis::Release</tt> method to return the object to its
* memory pool.
*
* On LwIP systems, this method must not be called with the LwIP stack
* lock already acquired.
*/
void UDPEndPoint::Free(void)
{
Close();
#if WEAVE_SYSTEM_CONFIG_USE_LWIP
DeferredFree(kReleaseDeferralErrorTactic_Die);
#else // !WEAVE_SYSTEM_CONFIG_USE_LWIP
Release();
#endif // !WEAVE_SYSTEM_CONFIG_USE_LWIP
}
/**
* A synonym for <tt>SendTo(addr, port, INET_NULL_INTERFACEID, msg, sendFlags)</tt>.
*/
INET_ERROR UDPEndPoint::SendTo(IPAddress addr, uint16_t port, Weave::System::PacketBuffer *msg, uint16_t sendFlags)
{
return SendTo(addr, port, INET_NULL_INTERFACEID, msg, sendFlags);
}
/**
* @brief Send a UDP message to the specified destination address.
*
* @param[in] addr the destination IP address
* @param[in] port the destination UDP port
* @param[in] intfId an optional network interface indicator
* @param[in] msg the packet buffer containing the UDP message
* @param[in] sendFlags optional transmit option flags
*
* @retval INET_NO_ERROR success: \c msg is queued for transmit.
*
* @retval INET_ERROR_NOT_SUPPORTED
* the system does not support the requested operation.
*
* @retval INET_ERROR_WRONG_ADDRESS_TYPE
* the destination address and the bound interface address do not
* have matching protocol versions or address type.
*
* @retval INET_ERROR_MESSAGE_TOO_LONG
* \c msg does not contain the whole UDP message.
*
* @retval INET_ERROR_OUTBOUND_MESSAGE_TRUNCATED
* On some platforms, only a truncated portion of \c msg was queued
* for transmit.
*
* @retval other
* another system or platform error
*
* @details
* If possible, then this method sends the UDP message \c msg to the
* destination \c addr (with \c intfId used as the scope
* identifier for IPv6 link-local destinations) and \c port with the
* transmit option flags encoded in \c sendFlags.
*
* Where <tt>(sendFlags & kSendFlag_RetainBuffer) != 0</tt>, calls
* <tt>Weave::System::PacketBuffer::Free</tt> on behalf of the caller, otherwise this
* method deep-copies \c msg into a fresh object, and queues that for
* transmission, leaving the original \c msg available after return.
*/
INET_ERROR UDPEndPoint::SendTo(IPAddress addr, uint16_t port, InterfaceId intfId, Weave::System::PacketBuffer *msg, uint16_t sendFlags)
{
IPPacketInfo pktInfo;
pktInfo.Clear();
pktInfo.DestAddress = addr;
pktInfo.DestPort = port;
pktInfo.Interface = intfId;
return SendMsg(&pktInfo, msg, sendFlags);
}
/**
* @brief Send a UDP message to a specified destination.
*
* @param[in] pktInfo source and destination information for the UDP message
* @param[in] msg a packet buffer containing the UDP message
* @param[in] sendFlags optional transmit option flags
*
* @retval INET_NO_ERROR
* success: \c msg is queued for transmit.
*
* @retval INET_ERROR_NOT_SUPPORTED
* the system does not support the requested operation.
*
* @retval INET_ERROR_WRONG_ADDRESS_TYPE
* the destination address and the bound interface address do not
* have matching protocol versions or address type.
*
* @retval INET_ERROR_MESSAGE_TOO_LONG
* \c msg does not contain the whole UDP message.
*
* @retval INET_ERROR_OUTBOUND_MESSAGE_TRUNCATED
* On some platforms, only a truncated portion of \c msg was queued
* for transmit.
*
* @retval other
* another system or platform error
*
* @details
* Send the UDP message in \c msg to the destination address and port given in
* \c pktInfo. If \c pktInfo contains an interface id, the message will be sent
* over the specified interface. If \c pktInfo contains a source address, the
* given address will be used as the source of the UDP message.
*
* Where <tt>(sendFlags & kSendFlag_RetainBuffer) != 0</tt>, calls
* <tt>Weave::System::PacketBuffer::Free</tt> on behalf of the caller, otherwise this
* method deep-copies \c msg into a fresh object, and queues that for
* transmission, leaving the original \c msg available after return.
*/
INET_ERROR UDPEndPoint::SendMsg(const IPPacketInfo *pktInfo, PacketBuffer *msg, uint16_t sendFlags)
{
INET_ERROR res = INET_NO_ERROR;
const IPAddress & destAddr = pktInfo->DestAddress;
INET_FAULT_INJECT(FaultInjection::kFault_Send,
if ((sendFlags & kSendFlag_RetainBuffer) == 0)
PacketBuffer::Free(msg);
return INET_ERROR_UNKNOWN_INTERFACE;
);
INET_FAULT_INJECT(FaultInjection::kFault_SendNonCritical,
if ((sendFlags & kSendFlag_RetainBuffer) == 0)
PacketBuffer::Free(msg);
return INET_ERROR_NO_MEMORY;
);
#if WEAVE_SYSTEM_CONFIG_USE_LWIP
if (sendFlags & kSendFlag_RetainBuffer)
{
// when retaining a buffer, the caller expects the msg to be
// unmodified. LwIP stack will normally prepend the packet
// headers as the packet traverses the UDP/IP/netif layers,
// which normally modifies the packet. We prepend a small
// pbuf to the beginning of the pbuf chain, s.t. all headers
// are added to the temporary space, just large enough to hold
// the transport headers. Careful reader will note:
//
// * we're actually oversizing the reserved space, the
// transport header is large enough for the TCP header which
// is larger than the UDP header, but it seemed cleaner than
// the combination of PBUF_IP for reserve space, UDP_HLEN
// for payload, and post allocation adjustment of the header
// space).
//
// * the code deviates from the existing PacketBuffer
// abstractions and needs to reach into the underlying pbuf
// code. The code in PacketBuffer also forces us to perform
// (effectively) a reinterpret_cast rather than a
// static_cast. JIRA WEAV-811 is filed to track the
// re-architecting of the memory management.
pbuf *msgCopy = pbuf_alloc(PBUF_TRANSPORT, 0, PBUF_RAM);
if (msgCopy == NULL)
{
return INET_ERROR_NO_MEMORY;
}
pbuf_chain(msgCopy, (pbuf *) msg);
msg = (PacketBuffer *)msgCopy;
}
// Lock LwIP stack
LOCK_TCPIP_CORE();
// Make sure we have the appropriate type of PCB based on the destination address.
res = GetPCB(destAddr.Type());
SuccessOrExit(res);
// Send the message to the specified address/port.
// If an outbound interface has been specified, call a specific version of the UDP sendto()
// function that accepts the target interface.
// If a source address has been specified, temporarily override the local_ip of the PCB.
// This results in LwIP using the given address being as the source address for the generated
// packet, as if the PCB had been bound to that address.
{
err_t lwipErr = ERR_VAL;
const IPAddress & srcAddr = pktInfo->SrcAddress;
const uint16_t & destPort = pktInfo->DestPort;
const InterfaceId & intfId = pktInfo->Interface;
#if LWIP_VERSION_MAJOR > 1 || LWIP_VERSION_MINOR >= 5
ip_addr_t lwipSrcAddr = srcAddr.ToLwIPAddr();
ip_addr_t lwipDestAddr = destAddr.ToLwIPAddr();
ip_addr_t boundAddr;
ip_addr_copy(boundAddr, mUDP->local_ip);
if (!ip_addr_isany(&lwipSrcAddr))
{
ip_addr_copy(mUDP->local_ip, lwipSrcAddr);
}
if (intfId != INET_NULL_INTERFACEID)
lwipErr = udp_sendto_if(mUDP, (pbuf *)msg, &lwipDestAddr, destPort, intfId);
else
lwipErr = udp_sendto(mUDP, (pbuf *)msg, &lwipDestAddr, destPort);
ip_addr_copy(mUDP->local_ip, boundAddr);
#else // LWIP_VERSION_MAJOR <= 1 && LWIP_VERSION_MINOR < 5
ipX_addr_t boundAddr;
ipX_addr_copy(boundAddr, mUDP->local_ip);
if (PCB_ISIPV6(mUDP))
{
ip6_addr_t lwipSrcAddr = srcAddr.ToIPv6();
ip6_addr_t lwipDestAddr = destAddr.ToIPv6();
if (!ip6_addr_isany(&lwipSrcAddr))
{
ipX_addr_copy(mUDP->local_ip, *ip6_2_ipX(&lwipSrcAddr));
}
if (intfId != INET_NULL_INTERFACEID)
lwipErr = udp_sendto_if_ip6(mUDP, (pbuf *)msg, &lwipDestAddr, destPort, intfId);
else
lwipErr = udp_sendto_ip6(mUDP, (pbuf *)msg, &lwipDestAddr, destPort);
}
#if INET_CONFIG_ENABLE_IPV4
else
{
ip4_addr_t lwipSrcAddr = srcAddr.ToIPv4();
ip4_addr_t lwipDestAddr = destAddr.ToIPv4();
ipX_addr_t boundAddr;
if (!ip_addr_isany(&lwipSrcAddr))
{
ipX_addr_copy(mUDP->local_ip, *ip_2_ipX(&lwipSrcAddr));
}
if (intfId != INET_NULL_INTERFACEID)
lwipErr = udp_sendto_if(mUDP, (pbuf *)msg, &lwipDestAddr, destPort, intfId);
else
lwipErr = udp_sendto(mUDP, (pbuf *)msg, &lwipDestAddr, destPort);
}
ipX_addr_copy(mUDP->local_ip, boundAddr);
#endif // INET_CONFIG_ENABLE_IPV4
#endif // LWIP_VERSION_MAJOR <= 1 || LWIP_VERSION_MINOR >= 5
if (lwipErr != ERR_OK)
res = Weave::System::MapErrorLwIP(lwipErr);
}
// Unlock LwIP stack
UNLOCK_TCPIP_CORE();
PacketBuffer::Free(msg);
#endif // WEAVE_SYSTEM_CONFIG_USE_LWIP
#if WEAVE_SYSTEM_CONFIG_USE_SOCKETS
// Make sure we have the appropriate type of socket based on the
// destination address.
res = GetSocket(destAddr.Type());
SuccessOrExit(res);
res = IPEndPointBasis::SendMsg(pktInfo, msg, sendFlags);
if ((sendFlags & kSendFlag_RetainBuffer) == 0)
PacketBuffer::Free(msg);
#endif // WEAVE_SYSTEM_CONFIG_USE_SOCKETS
exit:
WEAVE_SYSTEM_FAULT_INJECT_ASYNC_EVENT();
return res;
}
/**
* @brief Bind the endpoint to a network interface.
*
* @param[in] addrType the protocol version of the IP address.
*
* @param[in] intf indicator of the network interface.
*
* @retval INET_NO_ERROR success: endpoint bound to address
* @retval INET_NO_MEMORY insufficient memory for endpoint
* @retval INET_ERROR_NOT_IMPLEMENTED system implementation not complete.
*
* @retval INET_ERROR_UNKNOWN_INTERFACE
* On some platforms, the interface is not present.
*
* @retval other another system or platform error
*
* @details
* Binds the endpoint to the specified network interface IP address.
*
* On LwIP, this method must not be called with the LwIP stack lock
* already acquired.
*/
INET_ERROR UDPEndPoint::BindInterface(IPAddressType addrType, InterfaceId intfId)
{
INET_ERROR err = INET_NO_ERROR;
if (mState != kState_Ready && mState != kState_Bound)
return INET_ERROR_INCORRECT_STATE;
#if WEAVE_SYSTEM_CONFIG_USE_LWIP
//A lock is required because the LwIP thread may be referring to intf_filter,
//while this code running in the Inet application is potentially modifying it.
//NOTE: this only supports LwIP interfaces whose number is no bigger than 9.
LOCK_TCPIP_CORE();
// Make sure we have the appropriate type of PCB.
err = GetPCB(addrType);
SuccessOrExit(err);
err = LwIPBindInterface(mUDP, intfId);
UNLOCK_TCPIP_CORE();
SuccessOrExit(err);
#endif // WEAVE_SYSTEM_CONFIG_USE_LWIP
#if WEAVE_SYSTEM_CONFIG_USE_SOCKETS
// Make sure we have the appropriate type of socket.
err = GetSocket(addrType);
SuccessOrExit(err);
err = IPEndPointBasis::BindInterface(addrType, intfId);
SuccessOrExit(err);
#endif // WEAVE_SYSTEM_CONFIG_USE_SOCKETS
if (err == INET_NO_ERROR)
{
mState = kState_Bound;
}
exit:
return err;
}
void UDPEndPoint::Init(InetLayer *inetLayer)
{
IPEndPointBasis::Init(inetLayer);
}
/**
* Get the bound interface on this endpoint.
*
* @return InterfaceId The bound interface id.
*/
InterfaceId UDPEndPoint::GetBoundInterface(void)
{
#if WEAVE_SYSTEM_CONFIG_USE_LWIP
#if HAVE_LWIP_UDP_BIND_NETIF
return netif_get_by_index(mUDP->netif_idx);
#else
return mUDP->intf_filter;
#endif
#endif // WEAVE_SYSTEM_CONFIG_USE_LWIP
#if WEAVE_SYSTEM_CONFIG_USE_SOCKETS
return mBoundIntfId;
#endif // WEAVE_SYSTEM_CONFIG_USE_SOCKETS
}
uint16_t UDPEndPoint::GetBoundPort(void)
{
#if WEAVE_SYSTEM_CONFIG_USE_LWIP
return mUDP->local_port;
#endif // WEAVE_SYSTEM_CONFIG_USE_LWIP
#if WEAVE_SYSTEM_CONFIG_USE_SOCKETS
return mBoundPort;
#endif // WEAVE_SYSTEM_CONFIG_USE_SOCKETS
}
#if WEAVE_SYSTEM_CONFIG_USE_LWIP
void UDPEndPoint::HandleDataReceived(PacketBuffer *msg)
{
IPEndPointBasis::HandleDataReceived(msg);
}
INET_ERROR UDPEndPoint::GetPCB(IPAddressType addrType)
{
INET_ERROR err = INET_NO_ERROR;
// IMPORTANT: This method MUST be called with the LwIP stack LOCKED!
// If a PCB hasn't been allocated yet...
if (mUDP == NULL)
{
// Allocate a PCB of the appropriate type.
if (addrType == kIPAddressType_IPv6)
{
#if LWIP_VERSION_MAJOR > 1 || LWIP_VERSION_MINOR >= 5
mUDP = udp_new_ip_type(IPADDR_TYPE_V6);
#else // LWIP_VERSION_MAJOR <= 1 && LWIP_VERSION_MINOR < 5
mUDP = udp_new_ip6();
#endif // LWIP_VERSION_MAJOR <= 1 || LWIP_VERSION_MINOR >= 5
}
#if INET_CONFIG_ENABLE_IPV4
else if (addrType == kIPAddressType_IPv4)
{
#if LWIP_VERSION_MAJOR > 1 || LWIP_VERSION_MINOR >= 5
mUDP = udp_new_ip_type(IPADDR_TYPE_V4);
#else // LWIP_VERSION_MAJOR <= 1 && LWIP_VERSION_MINOR < 5
mUDP = udp_new();
#endif // LWIP_VERSION_MAJOR <= 1 || LWIP_VERSION_MINOR >= 5
}
#endif // INET_CONFIG_ENABLE_IPV4
else
{
ExitNow(err = INET_ERROR_WRONG_ADDRESS_TYPE);
}
// Fail if the system has run out of PCBs.
if (mUDP == NULL)
{
WeaveLogError(Inet, "Unable to allocate UDP PCB");
ExitNow(err = INET_ERROR_NO_MEMORY);
}
// Allow multiple bindings to the same port.
ip_set_option(mUDP, SOF_REUSEADDR);
}
// Otherwise, verify that the existing PCB is the correct type...
else
{
IPAddressType pcbAddrType;
// Get the address type of the existing PCB.
#if LWIP_VERSION_MAJOR > 1 || LWIP_VERSION_MINOR >= 5
switch (static_cast<lwip_ip_addr_type>(IP_GET_TYPE(&mUDP->local_ip)))
{
case IPADDR_TYPE_V6:
pcbAddrType = kIPAddressType_IPv6;
break;
#if INET_CONFIG_ENABLE_IPV4
case IPADDR_TYPE_V4:
pcbAddrType = kIPAddressType_IPv4;
break;
#endif // INET_CONFIG_ENABLE_IPV4
default:
ExitNow(err = INET_ERROR_WRONG_ADDRESS_TYPE);
}
#else // LWIP_VERSION_MAJOR <= 1 && LWIP_VERSION_MINOR < 5
#if INET_CONFIG_ENABLE_IPV4
pcbAddrType = PCB_ISIPV6(mUDP) ? kIPAddressType_IPv6 : kIPAddressType_IPv4;
#else // !INET_CONFIG_ENABLE_IPV4
pcbAddrType = kIPAddressType_IPv6;
#endif // !INET_CONFIG_ENABLE_IPV4
#endif // LWIP_VERSION_MAJOR <= 1 && LWIP_VERSION_MINOR < 5
// Fail if the existing PCB is not the correct type.
VerifyOrExit(addrType == pcbAddrType, err = INET_ERROR_WRONG_ADDRESS_TYPE);
}
exit:
return err;
}
#if LWIP_VERSION_MAJOR > 1 || LWIP_VERSION_MINOR >= 5
void UDPEndPoint::LwIPReceiveUDPMessage(void *arg, struct udp_pcb *pcb, struct pbuf *p, const ip_addr_t *addr, u16_t port)
#else // LWIP_VERSION_MAJOR <= 1 && LWIP_VERSION_MINOR < 5
void UDPEndPoint::LwIPReceiveUDPMessage(void *arg, struct udp_pcb *pcb, struct pbuf *p, ip_addr_t *addr, u16_t port)
#endif // LWIP_VERSION_MAJOR > 1 || LWIP_VERSION_MINOR >= 5
{
UDPEndPoint* ep = static_cast<UDPEndPoint*>(arg);
PacketBuffer* buf = reinterpret_cast<PacketBuffer*>(static_cast<void*>(p));
Weave::System::Layer& lSystemLayer = ep->SystemLayer();
IPPacketInfo* pktInfo = NULL;
pktInfo = GetPacketInfo(buf);
if (pktInfo != NULL)
{
#if LWIP_VERSION_MAJOR > 1 || LWIP_VERSION_MINOR >= 5
pktInfo->SrcAddress = IPAddress::FromLwIPAddr(*addr);
pktInfo->DestAddress = IPAddress::FromLwIPAddr(*ip_current_dest_addr());
#else // LWIP_VERSION_MAJOR <= 1
if (PCB_ISIPV6(pcb))
{
pktInfo->SrcAddress = IPAddress::FromIPv6(*(ip6_addr_t *)addr);
pktInfo->DestAddress = IPAddress::FromIPv6(*ip6_current_dest_addr());
}
#if INET_CONFIG_ENABLE_IPV4
else
{
pktInfo->SrcAddress = IPAddress::FromIPv4(*addr);
pktInfo->DestAddress = IPAddress::FromIPv4(*ip_current_dest_addr());
}
#endif // INET_CONFIG_ENABLE_IPV4
#endif // LWIP_VERSION_MAJOR <= 1
pktInfo->Interface = ip_current_netif();
pktInfo->SrcPort = port;
pktInfo->DestPort = pcb->local_port;
}
if (lSystemLayer.PostEvent(*ep, kInetEvent_UDPDataReceived, (uintptr_t)buf) != INET_NO_ERROR)
PacketBuffer::Free(buf);
}
#endif // WEAVE_SYSTEM_CONFIG_USE_LWIP
#if WEAVE_SYSTEM_CONFIG_USE_SOCKETS
INET_ERROR UDPEndPoint::GetSocket(IPAddressType aAddressType)
{
INET_ERROR lRetval = INET_NO_ERROR;
const int lType = (SOCK_DGRAM | SOCK_FLAGS);
const int lProtocol = 0;
lRetval = IPEndPointBasis::GetSocket(aAddressType, lType, lProtocol);
SuccessOrExit(lRetval);
exit:
return (lRetval);
}
SocketEvents UDPEndPoint::PrepareIO(void)
{
return (IPEndPointBasis::PrepareIO());
}
void UDPEndPoint::HandlePendingIO(void)
{
if (mState == kState_Listening && OnMessageReceived != NULL && mPendingIO.IsReadable())
{
const uint16_t lPort = mBoundPort;
IPEndPointBasis::HandlePendingIO(lPort);
}
mPendingIO.Clear();
}
#endif // WEAVE_SYSTEM_CONFIG_USE_SOCKETS
} // namespace Inet
} // namespace nl
|
196ff9b8f1f5ca8afcc00cf3a22a81c16f0ddb0a | 237197ec6d89a7eb62f6f0df98934f0202e86772 | /adobe/future/source/cursor_stack.hpp | 448b4ee5938352d9aef45444bfd36449750219ba | [] | no_license | ilelann/adobe_platform_libraries | acb7efab62cbae6fce61ef2c04cc080f6d085de7 | 55768ef67fdc24dd018e3e674dfe2d63754db5a9 | refs/heads/master | 2021-01-18T04:58:32.699240 | 2017-10-30T00:31:40 | 2018-07-19T06:42:11 | 20,827,777 | 2 | 0 | null | 2015-04-07T21:27:54 | 2014-06-14T07:54:34 | C++ | UTF-8 | C++ | false | false | 1,003 | hpp | cursor_stack.hpp | /*
Copyright 2013 Adobe
Distributed under the Boost Software License, Version 1.0.
(See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
*/
/****************************************************************************************************/
#ifndef ADOBE_CURSOR_STACK_HPP
#define ADOBE_CURSOR_STACK_HPP
/****************************************************************************************************/
#include <adobe/future/cursor.hpp>
/****************************************************************************************************/
void cursor_stack_push(adobe_cursor_t cursor);
void cursor_stack_pop();
adobe_cursor_t cursor_stack_top();
void cursor_stack_reset();
/****************************************************************************************************/
// ADOBE_CURSOR_STACK_HPP
#endif
/****************************************************************************************************/
|
a5ef5e0703267b1a3e135960d0e4adaf888569f7 | 5e62f8e21ec0ee786572f43c0eb80074e0d3bb5d | /Codingtest/SWEA/D3/5607_Combination.cpp | 5d7e016d268a40d3f96895f2a72232b404fa5d04 | [] | no_license | MinByeongChan/myMBC | f150b079cd1da93d5867742b77b48045743e56fc | 56089562cfbc2089d10ec4f64d6fc5c3ddcde35a | refs/heads/master | 2023-01-28T01:44:38.995070 | 2021-08-09T00:01:42 | 2021-08-09T00:01:59 | 131,692,700 | 2 | 0 | null | 2023-01-07T23:33:15 | 2018-05-01T08:43:40 | C++ | UTF-8 | C++ | false | false | 392 | cpp | 5607_Combination.cpp | #include <iostream>
using namespace std;
int main(int argc, char** argv) {
int T;
cin >> T;
for(int t=1; t<=T; t++) {
int N, R;
int result = 0;
cin >> N >> R;
int n=N, r=R;
int u=1, v=1;
for(int i=0; i<R; i++) {
u *= n;
v *= r;
n--;
r--;
}
result = u / v;
result %= 1234567891;
cout << "#"<< t<< " " << result << endl;
}
cin >> T;
return 0;
}
|
3d744ec4794cf1c7c45e89a49d08ec9bf92fce2b | c95937d631510bf5a18ad1c88ac59f2b68767e02 | /src/cpu/platform.hpp | 1de81f578e69be3448741e539843b06bb684bd85 | [
"BSD-3-Clause",
"MIT",
"Intel",
"BSL-1.0",
"Apache-2.0",
"BSD-2-Clause"
] | permissive | oneapi-src/oneDNN | 5cdaa8d5b82fc23058ffbf650eb2f050b16a9d08 | aef984b66360661b3116d9d1c1c9ca0cad66bf7f | refs/heads/master | 2023-09-05T22:08:47.214983 | 2023-08-09T07:55:23 | 2023-09-05T13:13:34 | 58,414,589 | 1,544 | 480 | Apache-2.0 | 2023-09-14T07:09:12 | 2016-05-09T23:26:42 | C++ | UTF-8 | C++ | false | false | 6,070 | hpp | platform.hpp | /*******************************************************************************
* Copyright 2020-2023 Intel Corporation
* Copyright 2020 Arm Ltd. and affiliates
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*******************************************************************************/
#ifndef CPU_PLATFORM_HPP
#define CPU_PLATFORM_HPP
#include "oneapi/dnnl/dnnl_config.h"
#include "common/c_types_map.hpp"
#include "common/impl_registration.hpp"
#include "common/z_magic.hpp"
// Possible architectures:
// - DNNL_X64
// - DNNL_AARCH64
// - DNNL_PPC64
// - DNNL_S390X
// - DNNL_RV64
// - DNNL_ARCH_GENERIC
// Target architecture macro is set to 1, others to 0. All macros are defined.
#if defined(DNNL_X64) + defined(DNNL_AARCH64) + defined(DNNL_PPC64) \
+ defined(DNNL_S390X) + defined(DNNL_RV64) \
+ defined(DNNL_ARCH_GENERIC) \
== 0
#if defined(__x86_64__) || defined(_M_X64)
#define DNNL_X64 1
#elif defined(__aarch64__)
#define DNNL_AARCH64 1
#elif defined(__powerpc64__) || defined(__PPC64__) || defined(_ARCH_PPC64)
#define DNNL_PPC64 1
#elif defined(__s390x__)
#define DNNL_S390X 1
#elif defined(__riscv)
#define DNNL_RV64 1
#else
#define DNNL_ARCH_GENERIC 1
#endif
#endif // defined(DNNL_X64) + ... == 0
#if defined(DNNL_X64) + defined(DNNL_AARCH64) + defined(DNNL_PPC64) \
+ defined(DNNL_S390X) + defined(DNNL_RV64) \
+ defined(DNNL_ARCH_GENERIC) \
!= 1
#error One and only one architecture should be defined at a time
#endif
#if !defined(DNNL_X64)
#define DNNL_X64 0
#endif
#if !defined(DNNL_AARCH64)
#define DNNL_AARCH64 0
#endif
#if !defined(DNNL_PPC64)
#define DNNL_PPC64 0
#endif
#if !defined(DNNL_S390X)
#define DNNL_S390X 0
#endif
#if !defined(DNNL_RV64)
#define DNNL_RV64 0
#endif
#if !defined(DNNL_ARCH_GENERIC)
#define DNNL_ARCH_GENERIC 0
#endif
// Helper macros: expand the parameters only on the corresponding architecture.
// Equivalent to: #if DNNL_$ARCH ... #endif
#define DNNL_X64_ONLY(...) Z_CONDITIONAL_DO(DNNL_X64, __VA_ARGS__)
#define DNNL_PPC64_ONLY(...) Z_CONDITIONAL_DO(DNNL_PPC64_ONLY, __VA_ARGS__)
#define DNNL_S390X_ONLY(...) Z_CONDITIONAL_DO(DNNL_S390X_ONLY, __VA_ARGS__)
#define DNNL_AARCH64_ONLY(...) Z_CONDITIONAL_DO(DNNL_AARCH64, __VA_ARGS__)
// Using RISC-V implementations optimized with RVV Intrinsics is optional for RISC-V builds
// and can be enabled with DNNL_ARCH_OPT_FLAGS="-march=<ISA-string>" option, where <ISA-string>
// contains V extension. If disabled, generic reference implementations will be used.
#if defined(DNNL_RV64) && defined(DNNL_RISCV_USE_RVV_INTRINSICS)
#define DNNL_RV64GCV_ONLY(...) __VA_ARGS__
#else
#define DNNL_RV64GCV_ONLY(...)
#endif
// Negation of the helper macros above
#define DNNL_NON_X64_ONLY(...) Z_CONDITIONAL_DO(Z_NOT(DNNL_X64), __VA_ARGS__)
// Using Arm Compute Library kernels is optional for AArch64 builds
// and can be enabled with the DNNL_AARCH64_USE_ACL CMake option
#if defined(DNNL_AARCH64) && defined(DNNL_AARCH64_USE_ACL)
#define DNNL_AARCH64_ACL_ONLY(...) __VA_ARGS__
#else
#define DNNL_AARCH64_ACL_ONLY(...)
#endif
// Primitive ISA section for configuring knobs.
// Note: MSVC preprocessor by some reason "eats" symbols it's not supposed to
// if __VA_ARGS__ is passed as empty. Then things happen like this for non-x64:
// impl0, AMX(X64_impl1), impl2, ... -> impl0 impl2, ...
// resulting in compilation error. Such problem happens for lists interleaving
// X64 impls and non-X64 for non-X64 build.
#if DNNL_X64
// Note: unlike workload or primitive set, these macros will work with impl
// items directly, thus, just make an item disappear, no empty lists.
#define __BUILD_AMX BUILD_PRIMITIVE_CPU_ISA_ALL || BUILD_AMX
#define __BUILD_AVX512 __BUILD_AMX || BUILD_AVX512
#define __BUILD_AVX2 __BUILD_AVX512 || BUILD_AVX2
#define __BUILD_SSE41 __BUILD_AVX2 || BUILD_SSE41
#else
#define __BUILD_AMX 0
#define __BUILD_AVX512 0
#define __BUILD_AVX2 0
#define __BUILD_SSE41 0
#endif
#if __BUILD_AMX
#define REG_AMX_ISA(...) __VA_ARGS__
#else
#define REG_AMX_ISA(...)
#endif
#if __BUILD_AVX512
#define REG_AVX512_ISA(...) __VA_ARGS__
#else
#define REG_AVX512_ISA(...)
#endif
#if __BUILD_AVX2
#define REG_AVX2_ISA(...) __VA_ARGS__
#else
#define REG_AVX2_ISA(...)
#endif
#if __BUILD_SSE41
#define REG_SSE41_ISA(...) __VA_ARGS__
#else
#define REG_SSE41_ISA(...)
#endif
namespace dnnl {
namespace impl {
namespace cpu {
namespace platform {
const char *get_isa_info();
dnnl_cpu_isa_t get_effective_cpu_isa();
status_t set_max_cpu_isa(dnnl_cpu_isa_t isa);
status_t set_cpu_isa_hints(dnnl_cpu_isa_hints_t isa_hints);
dnnl_cpu_isa_hints_t get_cpu_isa_hints();
bool DNNL_API prefer_ymm_requested();
// This call is limited to performing checks on plain C-code implementations
// (e.g. 'ref' and 'simple_primitive') and should avoid any x64 JIT
// implementations since these require specific code-path updates.
bool DNNL_API has_data_type_support(data_type_t data_type);
bool DNNL_API has_training_support(data_type_t data_type);
float DNNL_API s8s8_weights_scale_factor();
unsigned DNNL_API get_per_core_cache_size(int level);
unsigned DNNL_API get_num_cores();
#if DNNL_CPU_THREADING_RUNTIME == DNNL_RUNTIME_THREADPOOL
unsigned DNNL_API get_max_threads_to_use();
#endif
constexpr int get_cache_line_size() {
return 64;
}
int get_vector_register_size();
size_t get_timestamp();
} // namespace platform
// XXX: find a better place for these values?
enum {
PAGE_4K = 4096,
PAGE_2M = 2097152,
};
} // namespace cpu
} // namespace impl
} // namespace dnnl
#endif
|
20582dcd0479df36b2e326dc8b5cc5fb6833ecad | a485ee4bc1c3d64b049526e8a2b2b02bdeeb5428 | /src/span.hpp | eec5b118a648e6c6eca14046640ae5777beaa179 | [] | no_license | jamsonzan/tcmalloc | 0c94db8f3776d19385b6f69c29adea11e90060ce | 8866d6419244fbd83eb897e7b9ad87864bea849b | refs/heads/master | 2023-04-18T15:34:15.797784 | 2021-05-02T12:45:24 | 2021-05-02T12:45:24 | 363,432,777 | 4 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 2,906 | hpp | span.hpp | //
// Created by jamsonzan on 2021/4/29.
//
#ifndef TCMALLOC_SPAN_HPP
#define TCMALLOC_SPAN_HPP
#include <bits/stdc++.h>
#include <cstdint>
#include "fixed_allocator.hpp"
namespace tcmalloc {
class FreeList {
public:
FreeList() :head_(nullptr), free_count_(0) {}
void PushFront(void* ptr) {
*(reinterpret_cast<void **>(ptr)) = head_;
head_ = ptr;
free_count_++;
}
void* PopFront() {
if (Empty()) return nullptr;
void *result = head_;
head_ = *(reinterpret_cast<void **>(result));
free_count_--;
return result;
}
int FreeObjects() {
return free_count_;
}
void Clear() {
head_ = nullptr;
free_count_ = 0;
}
bool Empty() {
return free_count_ == 0;
}
private:
uint64_t free_count_;
void* head_;
};
struct Span {
Span* prev;
Span* next;
uint64_t page_id;
uint64_t npages;
uint64_t size_class;
uint64_t refcount;
FreeList freelist;
static const uint64_t spanPageSize = 8 * 1024;
enum Location { IN_USE, IN_NORMAL, IN_RETURNED };
uint64_t location;
uint64_t InitFreeList(uint64_t obj_bytes) {
assert(location == IN_USE);
freelist.Clear();
assert(freelist.Empty());
uint64_t ptr = reinterpret_cast<uint64_t>(reinterpret_cast<char *>(page_id * spanPageSize));
uint64_t limit = ptr + (npages * spanPageSize);
while (ptr + obj_bytes <= limit) {
freelist.PushFront((void*)ptr);
ptr += obj_bytes;
}
return freelist.FreeObjects();
}
static uint64_t PageIdFromPtr(void* ptr) {
return ((uint64_t)ptr)/spanPageSize;
}
};
static tcmalloc::FixedAllocator<Span> span_allocator;
Span* NewSpan(uint64_t page_id, uint64_t npages) {
Span* span = span_allocator.Alloc();
memset(span, 0, sizeof(span));
span->page_id = page_id;
span->npages = npages;
span->refcount = 0;
return span;
}
void DeleteSpan(Span* span) {
span_allocator.Free(span);
}
struct SpanLessCompare {
bool operator() (const Span* lhs, const Span* rhs) const {
if (lhs->npages < rhs->npages) return true;
if (rhs->npages < lhs->npages) return false;
return lhs->page_id < rhs->page_id;
}
};
typedef std::set<Span*, SpanLessCompare, tcmalloc::STLFixedAllocator<Span*, 0>> SpanSet;
void ListInit(Span* span) {
span->prev = span;
span->next = span;
}
bool ListEmpty(Span* span) {
return span->prev == span;
}
void ListRemove(Span* span) {
span->prev->next = span->next;
span->next->prev = span->prev;
span->prev = nullptr;
span->next = nullptr;
}
void ListInsert(Span* after, Span* span) {
span->prev = after;
span->next = after->next;
span->next->prev = span;
after->next = span;
}
}
#endif //TCMALLOC_SPAN_HPP
|
78bae3ea4f5fbe8279b57b8b02a0385a215f55b1 | 6d062a50b8f0617097769f33c1f3e9bec992e741 | /dlp_final/visual_system/src/get_click_position.cpp | c0b92faae0ef3d4f83ba67a0efe8e47e50b0a7fe | [] | no_license | sean85914/rl_pnp | 491c534510486834e17eece0857dc341f80f0938 | ca33894a5c1fb230e3755fd5d624f92151152a4d | refs/heads/master | 2023-02-16T03:18:02.789305 | 2021-01-16T16:55:49 | 2021-01-16T16:55:49 | 186,751,860 | 5 | 3 | null | null | null | null | UTF-8 | C++ | false | false | 6,269 | cpp | get_click_position.cpp | #include <ros/ros.h>
#include <tf/transform_listener.h>
// Message filters
#include <message_filters/subscriber.h>
#include <message_filters/synchronizer.h>
#include <message_filters/sync_policies/approximate_time.h>
// Message type
#include <sensor_msgs/PointCloud2.h>
#include <sensor_msgs/Image.h>
// PCL
#include <pcl_conversions/pcl_conversions.h>
#include <pcl/point_cloud.h>
#include <pcl/point_types.h>
// OpenCV
#include <opencv2/opencv.hpp>
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <cv_bridge/cv_bridge.h>
// DEBUG:
// 1. Visualize the result in RViz with sphere marker
// 2. Print execution time in ms
#define DEBUG 0
#ifdef DEBUG
#include <visualization_msgs/Marker.h>
#include <ctime>
ros::Publisher pub_marker;
visualization_msgs::Marker marker;
int ts; // time stamp for start time
#endif
// Subscribed topics string
const std::string IMAGE_STR = "/camera/rgb/image_raw";
const std::string CLOUD_STR = "/camera/depth_registered/points";
const std::string CV_WINDOW_NAME = "Test";
const int EPSILON = 7; // Should be odd number
// Click x and y coordinate in image plane
int click_pixel_x, click_pixel_y;
// Mouse event callback
void mouse_cb(int Event, int x, int y, int flags, void* param)
{
if(Event == CV_EVENT_LBUTTONUP) {
click_pixel_x = x;
click_pixel_y = y;
}
//std::cout << "Click on pixel: (" << x << ", " << y << ")" << std::endl;
}
// Subscriber callback:
// Input: image (of topic: /camera/rgb/image_raw)
// pointcloud (of topic: /camera/depth_registered/points)
void cb(const sensor_msgs::ImageConstPtr& image, const sensor_msgs::PointCloud2ConstPtr& in)
{
bool valid_res = true;
if(DEBUG) ts = clock();
// Convert PointCloud2 to pcl::PointCloud<pcl::PointXYZRGB>
pcl::PointCloud<pcl::PointXYZ> msg_;
pcl::fromROSMsg(*in, msg_);
// Convert Image to cv image
cv_bridge::CvImagePtr cv_ptr;
cv_ptr = cv_bridge::toCvCopy(image, sensor_msgs::image_encodings::BGR8);
// Show image
cv::imshow(CV_WINDOW_NAME, cv_ptr->image);
// If clicked...
if(click_pixel_x != -1 and click_pixel_y != -1){
// Get clicked pixel coordinate, use at function
double click_x = msg_.at(click_pixel_x, click_pixel_y).x,
click_y = msg_.at(click_pixel_x, click_pixel_y).y,
click_z = msg_.at(click_pixel_x, click_pixel_y).z;
if(std::isnan(click_x)){
// Handle NaN data
std::cerr << "\033[1;31mGet NaN from raw data, handling...\033[0m" << std::endl; // Red text
int count = 0;
double cali_x = 0, cali_y = 0, cali_z = 0;
for(int i=click_pixel_x-EPSILON/2; i<=click_pixel_x+EPSILON/2; ++i){
for(int j=click_pixel_y-EPSILON/2; j<=click_pixel_y+EPSILON/2; ++j){
if(!std::isnan(msg_.at(i, j).x)){
++count;
cali_x += msg_.at(i, j).x;
cali_y += msg_.at(i, j).y;
cali_z += msg_.at(i, j).z;
}
}
}
if(count!=0){
click_x = cali_x / (float)count;
click_y = cali_y / (float)count;
click_z = cali_z / (float)count;
}
else {
valid_res = false;
std::cerr << "\033[1;31mNeighborhood with 1-norm distance " << EPSILON/2 << " still get NaN \033[0m" << std::endl; // Red text
}
}
if(DEBUG) std::cout << "Execution time: " << (clock()-ts)/double(CLOCKS_PER_SEC)*1000 << " ms" << std::endl;
double click_x_tf, click_y_tf, click_z_tf;
if(valid_res){ // If the result is valid then print the information
std::cout << "Click on pixel: (" << click_pixel_x << ", " << click_pixel_y << ")" << std::endl;
std::cout << "Coordinate w.r.t. [" << in->header.frame_id << "]: (" <<
click_x << " " << click_y << " " << click_z << " )" << std::endl;
static tf::TransformListener listener;
tf::StampedTransform stf;
try {
listener.waitForTransform("base_link", in->header.frame_id, ros::Time(0),
ros::Duration(3.0));
listener.lookupTransform("base_link", in->header.frame_id, ros::Time(0), stf);
tf::Matrix3x3 rot_mat = tf::Matrix3x3(stf.getRotation());
tf::Vector3 trans = tf::Vector3(stf.getOrigin()),
vec = tf::Vector3(click_x, click_y, click_z),
vec_rot = rot_mat*vec,
vec_tf = vec_rot + trans;
click_x_tf = vec_tf.x(); click_y_tf = vec_tf.y(); click_z_tf = vec_tf.z();
}
catch(tf::TransformException ex){
ROS_ERROR("%s", ex.what());
click_x_tf = click_y_tf = click_z_tf = 0;
}
}
std::cout << "Coordinate w.r.t. [base_link]: (" << click_x_tf << ", "
<< click_y_tf << ", "
<< click_z_tf << ")" << std::endl;
if(DEBUG){
marker.pose.position.x = click_x;
marker.pose.position.y = click_y;
marker.pose.position.z = click_z;
pub_marker.publish(marker);
}
// Recover pixel coordinates to 0
click_pixel_x = -1; click_pixel_y = -1;
cv::waitKey(1.0);
}
}
int main(int argc, char** argv)
{
ros::init(argc, argv, "get_click_position");
ros::NodeHandle nh("~");
cv::namedWindow(CV_WINDOW_NAME);
cv::setMouseCallback(CV_WINDOW_NAME, mouse_cb, NULL);
message_filters::Subscriber<sensor_msgs::Image> image_sub(nh, IMAGE_STR, 1);
message_filters::Subscriber<sensor_msgs::PointCloud2> cloud_sub(nh, CLOUD_STR, 1);
typedef message_filters::sync_policies::ApproximateTime\
<sensor_msgs::Image, sensor_msgs::PointCloud2> MySyncPolicy;
message_filters::Synchronizer<MySyncPolicy> sync(MySyncPolicy(10), image_sub, cloud_sub);
sync.registerCallback(boost::bind(&cb, _1, _2));
if(DEBUG){
marker.header.frame_id = "camera_rgb_optical_frame";
marker.type = visualization_msgs::Marker::SPHERE;
marker.action = visualization_msgs::Marker::ADD;
marker.pose.orientation.w = 1.0;
marker.scale.x = 0.01; marker.scale.y = 0.01; marker.scale.z = 0.01;
marker.color.r = 1.0; marker.color.a = 1.0;
pub_marker = nh.advertise<visualization_msgs::Marker>("visualize_point", 1);
}
ros::spin();
return 0;
}
|
8e27878957c1e4440e232d0b9459da0c301014f2 | d30b46ddd5703fa67a27144367a77a1868c2e070 | /main.cpp | f84b694e4da518e75801c526ae59bae1205f77e0 | [
"MIT"
] | permissive | hansfilipelo/hashTable | 047b0a932808287440452bd4e7c8aef72e888644 | c2a352a2e1fcedd4042034544089f6d2fcdac3f9 | refs/heads/master | 2020-12-30T11:14:47.015491 | 2014-12-04T14:56:46 | 2014-12-04T14:56:46 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 428 | cpp | main.cpp | #include "hash.h"
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main(){
Hash dict;
dict.put("Erik","+46 73-682 43 06");
dict.put("Erhl","Pooo");
dict.put("David","076-017 71 15");
dict.put("Erik","SlowCPU");
string input;
cout << "Enter name: " << endl;
getline(cin,input);
cout << dict.get(input) << endl;
return 0;
}
|
1ef3e4c5d6b23de019a09aba01de084dd9f215f5 | 9369318cdbde33f5910c6de3736f1d07400cf276 | /112A.cpp | 47aa2deab0b29e0358811b19b67244c3f4408479 | [] | no_license | cwza/codeforces | cc58c646383a201e10422ec80567b52bef4a0da9 | e193f5d766e8ddda6cdc8a43b9f1826eeecfc870 | refs/heads/master | 2023-04-11T12:22:04.555974 | 2021-04-22T04:45:20 | 2021-04-22T04:45:20 | 352,477,628 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 424 | cpp | 112A.cpp | #include <bits/stdc++.h>
using namespace std;
typedef long long ll;
int main() {
ios::sync_with_stdio(0);
cin.tie(0);
string s1, s2;
cin >> s1 >> s2;
for(int i = 0; i < s1.size(); ++i) {
s1[i] = tolower(s1[i]);
s2[i] = tolower(s2[i]);
}
int a = s1.compare(s2);
if(a < 0) {
cout << -1;
} else if(a==0) {
cout << 0;
} else {
cout << 1;
}
} |
f07971dc7236fcad611ecf8d49a5bd05d361d670 | 0676032b18133a46adeace89196bc769a87500d1 | /2019-2020第二学期训练/AtCoder Beginner Contest 157/E.Simple String Queries.cpp | 806f87af014630f9779d8c0b57c5de60a2d312b9 | [] | no_license | zhushaoben/training | ce47c19934f67fc21f4571f99973d16561ede195 | 530f2b5dc1a2d1e4a02c22f034e251160d0b42af | refs/heads/master | 2021-07-11T22:32:54.227626 | 2020-10-30T12:49:24 | 2020-10-30T12:49:24 | 213,320,465 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 752 | cpp | E.Simple String Queries.cpp | #include<bits/stdc++.h>
using namespace std;
const int N = 5e5+5;
int c[26][N];char s[N];
inline int lowbit(int x){return x&(-x);}
void add(int i,int x,int num){
while(x<=N){
c[i][x]+=num;
x+=lowbit(x);
}
}
int sum(int i,int x){
int ans=0;
while(x){
ans+=c[i][x];
x-=lowbit(x);
}
return ans;
}
int main(){
int n,m,op,x,y;char y1[2];
scanf("%d%s",&n,s+1);
for(int i=1;s[i];i++)add(s[i]-'a',i,1);
scanf("%d",&m);
for(int i=0;i<m;i++){
scanf("%d",&op);
if(op==1){
scanf("%d%s",&x,y1);
add(s[x]-'a',x,-1);
s[x]=*y1;add(s[x]-'a',x,1);
}
else{
int ans=0;
scanf("%d%d",&x,&y);
for(int i=0;i<26;i++)if(sum(i,y)-sum(i,x-1))ans++;
printf("%d\n",ans);
}
}
return 0;
}
|
65ef2729fe4662652b110eb19d8ea9182bca5696 | c5b300b8b7958c0e4f99c54740fa56a027a3e85f | /visualloc/localizer/src/features/ORB_loader.hh | ea486b1eb42fd59c47786df9141774ecbde41cf4 | [] | no_license | abmmusa/visualloc | e4feabdc724d7e8959260e5869778fdd3438b4a2 | 267ffb2a4c60f2a72fb0a4e847cfea4b91d831dc | refs/heads/master | 2021-01-01T19:21:43.081215 | 2017-07-27T19:08:11 | 2017-07-27T19:08:11 | 98,570,827 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,181 | hh | ORB_loader.hh | /*===========================================================================*\
* *
* ACG Localizer *
* Copyright (C) 2011 by Computer Graphics Group, RWTH Aachen *
* www.rwth-graphics.de *
* *
*---------------------------------------------------------------------------*
* This file is part of ACG Localizer *
* *
* ACG Localizer is free software: you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation, either version 3 of the License, or *
* (at your option) any later version. *
* *
* ACG Localizer is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with ACG Localizer. If not, see <http://www.gnu.org/licenses/>. *
* *
\*===========================================================================*/
#ifndef ORB_LOADER_HH
#define ORB_LOADER_HH
/**
* Class to read SIFT features from the text files generated by
* David Lowe's binary ( available at http://www.cs.ubc.ca/~lowe/keypoints/).
*
* IMPORTANT NOTE: The SIFT loader keeps the coordinate systems of the binaries. For example,
* the origin of the coordinate system used by David Lowe is in the upper left of the image.
*
* author : Torsten Sattler (tsattler@cs.rwth-aachen.de)
* date : 09-26-2011
**/
#include <vector>
#include <stdint.h>
#include "ORB_keypoint.hh"
class ORB_loader
{
public:
//! constructor
ORB_loader( );
//! destructor
~ORB_loader( );
//! load features from a file with a given format
void load_features( const char *filename, ORB_FORMAT format );
//! clears all data loaded so far
void clear_data( );
//! returns the number of features loaded
uint32_t get_nb_features( );
//! get access to a vector containg the descriptors (stored as chars)
std::vector< unsigned char* >& get_descriptors( );
//! get the keypoints
std::vector< ORB_keypoint >& get_keypoints( );
private:
std::vector< ORB_keypoint > mKeypoints;
std::vector< unsigned char* > mDescriptors;
uint32_t mNbFeatures;
bool load_default_features( const char *filename );
};
#endif
|
8440e8f0f4138bd105e609784f148cc0c594d8e1 | e64de6e15e83104511203b19cddf533ab0b83858 | /src/parser/scanner.h | 014c128c6cd744384e023c84aca0d7187fb8737c | [] | no_license | brn/yatsc | 49b998ed4a55795fd28bd6a6a3964957e1740316 | d3fe64ea4b979ef93c9239b46bc8f9672faabe98 | refs/heads/master | 2021-01-01T19:00:44.883959 | 2015-03-30T00:53:09 | 2015-03-30T00:53:09 | 20,675,007 | 4 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 9,956 | h | scanner.h | // The MIT License (MIT)
//
// Copyright (c) 2013 Taketoshi Aono(brn)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#ifndef PARSER_SCANNER_H_
#define PARSER_SCANNER_H_
#include <sstream>
#include "character.h"
#include "token.h"
#include "utfstring.h"
#include "lineterminator-state.h"
#include "literalbuffer.h"
#include "../utils/stl.h"
#include "../compiler-option.h"
#include "../compiler/module-info.h"
#if defined(DEBUG) || defined(UNIT_TEST)
#define TOKEN_ERROR(message) \
(void)[&]{StringStream ss;ss << message << '\n' << __FILE__ << ":" << __LINE__ << "\n";Error(ss.str().c_str());}()
#else
#define TOKEN_ERROR(message) \
(void)[&]{StringStream ss;ss << message << '\n';Error(ss.str().c_str());}()
#endif
#define ILLEGAL_TOKEN() TOKEN_ERROR("Illegal Token");
namespace yatsc {
template <typename UCharInputIterator>
class Scanner: public ErrorReporter, private Uncopyable, private Unmovable {
public:
/**
* @param source The source file content.
*/
Scanner(UCharInputIterator it,
UCharInputIterator end,
LiteralBuffer* literal_buffer,
const CompilerOption& compilation_option);
/**
* Scan the source file from the current position to the next token position.
*/
Token* Scan();
Token* Peek();
YATSC_CONST_GETTER(size_t, line_number, scanner_source_position_.current_line_number())
// Check whether current token is regular expression or not.
// If current token is regular expression return TS_REGULAR_EXPR,
// if not regular expr return nullptr.
Token* CheckRegularExpression(Token* token_info);
void EnableNestedGenericTypeScanMode() {
generic_type_++;
}
void DisableNestedGenericTypeScanMode() {
generic_type_--;
}
bool IsGenericMode() {return generic_type_ > 0;}
int nested_generic_count() {return generic_type_;}
template <typename T>
void SetErrorCallback(T callback) {error_callback_ = callback;}
template <typename T>
void SetReferencePathCallback(T callback) {reference_path_callback_ = callback;}
private:
class ScannerSourcePosition {
public:
ScannerSourcePosition()
: start_position_(0),
current_position_(0),
current_line_number_(1),
start_line_number_(1) {}
YATSC_CONST_GETTER(size_t, start_position, start_position_)
YATSC_CONST_GETTER(size_t, current_position, current_position_)
YATSC_CONST_GETTER(size_t, current_line_number, current_line_number_)
YATSC_CONST_GETTER(size_t, start_line_number, start_line_number_)
YATSC_INLINE void AdvancePosition(size_t pos) YATSC_NOEXCEPT {current_position_ += pos;}
YATSC_INLINE void AdvanceLine() YATSC_NOEXCEPT {
current_line_number_++;
current_position_ = 1;
}
YATSC_INLINE void UpdateStartPosition() YATSC_NOEXCEPT {
start_position_ = current_position_;
start_line_number_ = current_line_number_;
}
private:
size_t start_position_;
size_t current_position_;
size_t current_line_number_;
size_t start_line_number_;
};
public:
class RecordedCharPosition {
public:
RecordedCharPosition(const ScannerSourcePosition& ssp, const UCharInputIterator& it,
const UChar& uchar, const UChar& lookahead)
: ssp_(ssp),
ucii_(it),
uchar_(uchar),
lookahead_(lookahead){}
RecordedCharPosition(const RecordedCharPosition& rcp) = default;
YATSC_CONST_GETTER(ScannerSourcePosition, ssp, ssp_)
YATSC_CONST_GETTER(UCharInputIterator, ucii, ucii_)
YATSC_CONST_GETTER(UChar, current, uchar_)
YATSC_CONST_GETTER(UChar, lookahead, lookahead_)
private:
ScannerSourcePosition ssp_;
UCharInputIterator ucii_;
UChar uchar_;
UChar lookahead_;
};
RecordedCharPosition char_position() YATSC_NO_SE {
return RecordedCharPosition(scanner_source_position_, it_, char_, lookahead1_);
}
void RestoreScannerPosition(const RecordedCharPosition& rcp);
private:
void LineFeed() {
scanner_source_position_.AdvanceLine();
}
void BeforeScan() {
if (unscaned_) {
unscaned_ = false;
Advance();
SkipSignature();
SkipWhiteSpace();
}
error_ = false;
line_terminator_state_.Clear();
scanner_source_position_.UpdateStartPosition();
}
bool ErrorOccurred() const {return error_;}
void AfterScan() {
last_multi_line_comment_.Clear();
SkipWhiteSpace();
token_info_.set_line_terminator_state(line_terminator_state_);
}
bool DoScan();
/**
* Scan string literal.
*/
void ScanStringLiteral();
/**
* Scan digit literal(includes Hex, Double, Integer)
*/
void ScanDigit();
/**
* Scan identifier.
*/
void ScanIdentifier();
void ScanInteger();
void ScanHex();
void ScanOperator();
void ScanArithmeticOperator(TokenKind type1, TokenKind type2, TokenKind normal, bool has_let = true);
void ScanOctalLiteral();
void ScanBinaryLiteral();
bool ScanUnicodeEscapeSequence(UtfString*, bool in_string_literal);
void ScanRegularExpression();
bool ConsumeLineBreak();
UC16 ScanHexEscape(const UChar& uchar, int len, bool* success);
void ScanLogicalOperator(TokenKind type1, TokenKind type2, TokenKind type3) {
if (lookahead1_ == char_) {
Advance();
return BuildToken(type1);
}
if (lookahead1_ == unicode::u32('=')) {
Advance();
return BuildToken(type2);
}
BuildToken(type3);
}
void ScanBitwiseOrComparationOperator(
TokenKind type1, TokenKind type2, TokenKind type3, TokenKind normal, TokenKind equal_comparator, bool has_u = false);
void ScanEqualityComparatorOrArrowGlyph(bool not = false);
bool ScanAsciiEscapeSequence(UtfString* str);
template <typename T>
int ToHexValue(const T& uchar) YATSC_NO_SE;
YATSC_INLINE bool IsEnd() const {
return it_ == end_;
}
bool SkipWhiteSpace();
bool SkipWhiteSpaceOnly();
bool SkipSingleLineComment();
void SkipTripleSlashComment();
bool SkipMultiLineComment();
bool SkipSignature();
void UpdateToken() {
if (last_multi_line_comment_.utf8_length() > 0) {
token_info_.set_multi_line_comment(Heap::NewHandle<UtfString>(last_multi_line_comment_));
}
last_multi_line_comment_.Clear();
token_info_.ClearValue();
token_info_.set_source_position(CreateSourcePosition());
}
void Error(const char* message) {
error_ = true;
if (error_callback_) {
error_callback_(message, CreateSourcePosition());
}
}
YATSC_INLINE void Illegal() {
Error("Illegal token.");
}
YATSC_INLINE SourcePosition CreateSourcePosition() {
return SourcePosition(scanner_source_position_.start_position(),
scanner_source_position_.current_position(),
scanner_source_position_.start_line_number(),
scanner_source_position_.current_line_number());
}
void BuildToken(TokenKind type, const UtfString& utf_string) {
UpdateToken();
auto literal = literal_buffer_->InsertValue(utf_string);
token_info_.set_value(literal);
token_info_.set_type(type);
}
void BuildToken(TokenKind type) {
UpdateToken();
token_info_.set_type(type);
}
void Advance();
void Skip() {
while (!Character::IsWhiteSpace(char_, lookahead1_) &&
Character::GetLineBreakType(char_, lookahead1_) == Character::LineBreakType::NONE &&
char_ != unicode::u32('\0')) {
Advance();
}
}
void Skip(UtfString& utf_string) {
while (!Character::IsWhiteSpace(char_, lookahead1_) &&
char_ != unicode::u32('\0')) {
Advance();
utf_string += char_;
}
}
bool unscaned_;
bool error_;
int generic_type_;
ScannerSourcePosition scanner_source_position_;
LineTerminatorState line_terminator_state_;
UCharInputIterator it_;
UCharInputIterator end_;
Token token_info_;
Token peeked_info_;
UChar prev_;
UChar char_;
UChar lookahead1_;
UtfString last_multi_line_comment_;
LiteralBuffer* literal_buffer_;
const CompilerOption& compiler_option_;
std::function<void(const Literal*)> reference_path_callback_;
std::function<void(const char* message, const SourcePosition& source_position)> error_callback_;
};
}
#include "scanner-inl.h"
#undef TOKEN_ERROR
#undef ILLEGAL_TOKEN
#endif
|
72c61d5cc6b2293b55f7db72ca8aca7e47f86018 | 97864bcb16c64fa86739a8d06b30b889671dde8e | /C++_code/第九章/3.cpp | 99b28219085a496ebedf2fe401d04a7f504969be | [] | no_license | liuhangyang/Study_notes | 67214ea88f8b04275d794b0c5dd3a2ab0437179a | 734d216ff116ce451d50c2a2e0f390b0a9a975d3 | refs/heads/master | 2021-01-10T08:44:19.007133 | 2016-03-06T02:31:09 | 2016-03-06T02:31:09 | 47,327,131 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 620 | cpp | 3.cpp | /*************************************************************************
> File Name: 3.cpp
> Author:yang
> Mail:yanglongfei@xiyoulinux.org
> Created Time: 2015年12月15日 星期二 15时26分53秒
************************************************************************/
#include<iostream>
#include <list>
#include <vector>
using namespace std;
int main(int argc,char *argv[])
{
list<int> s={1,2,3,4,5,6,7,8,9};
vector<int> m={9,8,7,6,5,4,3,2,1};
vector<double> t(m.begin(),m.end());
// vector<double> t=m; 错误
for(auto x:t){
cout << x;
}
cout << endl;
return 0;
}
|
34d632e56213851972b171aaf65b9407cace7a9a | 6b2a8dd202fdce77c971c412717e305e1caaac51 | /solutions_5658571765186560_1/C++/airsharks/Source.cpp | 85c66d7506f9050b4c4250a94dd1b53610903589 | [] | no_license | alexandraback/datacollection | 0bc67a9ace00abbc843f4912562f3a064992e0e9 | 076a7bc7693f3abf07bfdbdac838cb4ef65ccfcf | refs/heads/master | 2021-01-24T18:27:24.417992 | 2017-05-23T09:23:38 | 2017-05-23T09:23:38 | 84,313,442 | 2 | 4 | null | null | null | null | UTF-8 | C++ | false | false | 2,710 | cpp | Source.cpp | #include <stdio.h>
int main()
{
int N;
char t;
scanf_s("%d", &N);
FILE *fp;
fopen_s(&fp, "out.out", "wt+");
for (int Case = 1; Case <= N; Case++)
{
int X, R, C;
scanf_s("%d %d %d", &X, &R, &C);
switch (X)
{
case 1:
{
fprintf(fp, "Case #%d: GABRIEL\n", Case);
printf("Case #%d: GABRIEL\n", Case);
break;
}
case 2:
{
if (R*C%X != 0)
{
fprintf(fp, "Case #%d: RICHARD\n", Case);
printf("Case #%d: RICHARD\n", Case);
}
else
{
if (R*C >= 2)
{
fprintf(fp, "Case #%d: GABRIEL\n", Case);
printf("Case #%d: GABRIEL\n", Case);
}
else
{
fprintf(fp, "Case #%d: RICHARD\n", Case);
printf("Case #%d: RICHARD\n", Case);
}
}
break;
}
case 3:
{
if (R*C%X != 0)
{
fprintf(fp, "Case #%d: RICHARD\n", Case);
printf("Case #%d: RICHARD\n", Case);
}
else
{
if (R*C >3 && R>1 && C>1)
{
fprintf(fp, "Case #%d: GABRIEL\n", Case);
printf("Case #%d: GABRIEL\n", Case);
}
else
{
fprintf(fp, "Case #%d: RICHARD\n", Case);
printf("Case #%d: RICHARD\n", Case);
}
}
break;
}
case 4:
{
if (R*C%X != 0)
{
fprintf(fp, "Case #%d: RICHARD\n", Case);
printf("Case #%d: RICHARD\n", Case);
}
else
{
if (R*C >= 12 && R > 2 && C > 2)
{
fprintf(fp, "Case #%d: GABRIEL\n", Case);
printf("Case #%d: GABRIEL\n", Case);
}
else
{
fprintf(fp, "Case #%d: RICHARD\n", Case);
printf("Case #%d: RICHARD\n", Case);
}
}
break;
}
case 5:
{
if (R*C%X != 0)
{
fprintf(fp, "Case #%d: RICHARD\n", Case);
printf("Case #%d: RICHARD\n", Case);
}
else
{
if (R*C >= 15 && R>3 && C>3)
{
fprintf(fp, "Case #%d: GABRIEL\n", Case);
printf("Case #%d: GABRIEL\n", Case);
}
else
{
fprintf(fp, "Case #%d: RICHARD\n", Case);
printf("Case #%d: RICHARD\n", Case);
}
}
break;
}
case 6:
{
if (R*C%X != 0)
{
fprintf(fp, "Case #%d: RICHARD\n", Case);
printf("Case #%d: RICHARD\n", Case);
}
else
{
//if (R%X == 0 || C%X == 0)
{
if (R*C >= 24 && R >3 & C >3)
{
fprintf(fp, "Case #%d: GABRIEL\n", Case);
printf("Case #%d: GABRIEL\n", Case);
}
else
{
fprintf(fp, "Case #%d: RICHARD\n", Case);
printf("Case #%d: RICHARD\n", Case);
}
}
}
break;
}
default:
{
fprintf(fp, "Case #%d: RICHARD\n", Case);
printf("Case #%d: RICHARD\n", Case);
break;
}
}
}
fclose(fp);
N = getchar();
} |
1e830b7a4a71add60fd30520907810adc1e79ef8 | 78b28019e10962bb62a09fa1305264bbc9a113e3 | /common/data_structures/segment_tree/action/rotate_vector__sum.h | 9c26a8caab19af9eb00f8b1333168e0dc97935e4 | [
"MIT"
] | permissive | Loks-/competitions | 49d253c398bc926bfecc78f7d468410702f984a0 | 26a1b15f30bb664a308edc4868dfd315eeca0e0b | refs/heads/master | 2023-06-08T06:26:36.756563 | 2023-05-31T03:16:41 | 2023-05-31T03:16:41 | 135,969,969 | 5 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 1,106 | h | rotate_vector__sum.h | #pragma once
#include "common/data_structures/segment_tree/action/none.h"
namespace ds {
namespace st {
namespace action {
// Support only VectorStaticSize from LinearAlgebra.
class RotateVectorSum : public None {
protected:
template <class TVector>
static void Rotate(TVector& v, unsigned r) {
if (r == 0) return;
thread_local TVector vt;
unsigned size = v.Size();
for (unsigned i = 0; i < size; ++i) vt((i + r) % size) = v(i);
v.swap(vt);
}
public:
using TBase = None;
using TSelf = RotateVectorSum;
static const bool modify_data = true;
unsigned r = 0;
bool IsEmpty() const { return r == 0; }
void Clear() { r = 0; };
template <class TNode>
void Add(TNode* node, unsigned _r) {
Rotate(node->info.sum, _r);
r = (r + _r) % node->info.sum.Size();
}
template <class TNode>
void Apply(TNode* node) {
if (IsEmpty()) return;
if (node->IsLeaf()) {
Rotate(node->GetData(), r);
} else {
node->l->AddAction(r);
node->r->AddAction(r);
}
r = 0;
}
};
} // namespace action
} // namespace st
} // namespace ds
|
8dcf84c16af7979c64789bf90fc54bcbbcfac90d | 07f3097cb44572349f6ecafce44e44cb9435cf70 | /pao/DX11/FrameworkDX11.cpp | f1cbc0322e007c2eae4a658129931939e926e508 | [] | no_license | etsuhiro/avs | 0a8ffce362ebe77c3705311f9dd4b84797959573 | 956a6af0b71ef5e612134d1d6daf981dc5570342 | refs/heads/master | 2021-07-12T02:44:00.623140 | 2015-12-23T17:07:41 | 2015-12-23T17:07:41 | 30,864,183 | 0 | 0 | null | null | null | null | SHIFT_JIS | C++ | false | false | 1,111 | cpp | FrameworkDX11.cpp | #include "DX11/FrameworkDX11.h"
using namespace pao;
FrameworkDX11::FrameworkDX11(HINSTANCE hInstance)
: FrameworkWindows(hInstance)
{
}
FrameworkDX11::~FrameworkDX11()
{
}
BOOL FrameworkDX11::Setup(HWND hWnd)
{
return TRUE;
}
LRESULT FrameworkDX11::OnCreate(HWND hWnd, WPARAM wParam, LPARAM lParam)
{
// WM_NCCREATEでは早すぎてdx11の初期化ができませんのでWM_CREATEで行います。
if (dx11.InitDX11(hWnd) == S_OK)
Setup(hWnd);
return 0;
}
int FrameworkDX11::MainLoop()
{
MSG msg = { 0 };
while (msg.message != WM_QUIT)
{
if (PeekMessage(&msg, NULL, 0U, 0U, PM_REMOVE)){
TranslateMessage(&msg);
DispatchMessage(&msg);
}
else {
// Update();
dx11.Clear();
Render(dx11.DeviceContext());
dx11.Flip();
}
}
dx11.ExitDX11();
return (int)msg.wParam;
}
// ウィンドウリサイズ中はレンダーに処理が移行しないので、中で描画してみた
void FrameworkDX11::OnSize(HWND hwnd, UINT flag, int width, int height)
{
dx11.Clear();
Render(dx11.DeviceContext());
dx11.Flip();
}
void FrameworkDX11::Render(ID3D11DeviceContext*)
{
}
|
3c5ad945d1e59fcf9ecb3e18aed29b49cbc33264 | 6d34d2e96149d365847a58965d270c32173b1c87 | /scratch/aodv/cluster.h | 058850b486e11a867797dc7aac26e9ebed36acac | [] | no_license | jasoncyu/aodv-ids | b302e6f6131d1b8cd6e460acf6d90985158f116c | a23957a9e27a4883a7293ae03a326539a4a15ab8 | refs/heads/master | 2021-01-19T13:46:24.086207 | 2012-08-10T02:18:32 | 2012-08-10T02:18:32 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 448 | h | cluster.h | // cluster.h
//
#ifndef LZZ_cluster_h
#define LZZ_cluster_h
#define LZZ_INLINE inline
#include "common.h"
#include <iostream>
#include <stdint.h>
struct Cluster
{
Traffic centroid;
uint32_t count;
double w;
bool anomalous;
//used for inspection afterwards;
double criteria;
uint32_t size ();
bool add (Traffic t);
Cluster ();
Cluster(Traffic t);
static double Distance (Traffic t1, Traffic t2);
};
#undef LZZ_INLINE
#endif |
9369aa78d26a3cdc035aefe4f235bf874d8a7aa0 | b22679cc97887e7579c42c0f753563c21e2235cd | /src/cpp_sort.cpp | 360a918729c66e9ac899183e291b363c7a662436 | [] | no_license | kjn-void/sort_bench | c756f67890fda67ef18be3cb51ee2fd697361617 | 44f1d29a6157eabaceb1f2d3cb86c759d4039ae4 | refs/heads/main | 2023-06-16T09:14:07.871567 | 2021-07-03T19:51:59 | 2021-07-03T19:51:59 | 382,696,580 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 114 | cpp | cpp_sort.cpp | #include "cpp_sort.hpp"
#include <algorithm>
void cpp_sort(uint32_t *v, size_t sz) {
std::sort(v, v + sz);
}
|
83337b833d93cd0a08c4c92b48714ce30262a798 | 00ca9d7747eb8a7456a46f08c6417d59b185d5ab | /CG_Curs_Fire/Geometry/Prims3d.h | fbbb58f1cecec2541e7e77231fcb4680895934cf | [] | no_license | xammi/Curs_Fire | ad1a72dbf76b1def84f76fc87de1b5bcc591ed1f | fe09b52e2fe74e4ad102a44aaba1f163f640026a | refs/heads/master | 2020-05-16T21:59:18.748947 | 2014-12-09T16:14:04 | 2014-12-09T16:14:04 | 21,610,161 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,118 | h | Prims3d.h | #ifndef POINT3D_H
#define POINT3D_H
#include "includes.h"
enum class Axis { OX, OY, OZ };
//-------------------------------------------------------------------------------------------------
class Point3D
{
public:
Point3D();
Point3D(double, double, double);
public:
double X, Y, Z;
};
class Vector3D {
public:
Vector3D();
Vector3D(double, double,double);
double abs() const;
Vector3D single() const;
public:
double X, Y, Z;
};
typedef QVector<QPoint> QPoints;
typedef QVector<Point3D> Points3D;
double dist(const QPoint &, const QPoint &);
double dist(const Point3D &, const Point3D &);
Point3D operator +(const Point3D &, const Vector3D &);
Point3D operator -(const Point3D &, const Vector3D &);
Vector3D operator -(const Point3D &, const Point3D &);
Vector3D operator *(const Vector3D &, const double);
double scalMul(const Vector3D &, const Vector3D &);
double destructBy(const Vector3D &, const Vector3D &);
QString toString(const Point3D &);
QString toString(const Vector3D &);
//-------------------------------------------------------------------------------------------------
class Plane3D {
public:
Plane3D();
Plane3D(double, double, double, double);
Plane3D(const Point3D &, const Vector3D &);
Point3D project(const Point3D &) const;
double dist(const Point3D &) const;
public:
double A, B, C, D;
};
class Polygon3D {
public:
Polygon3D() {}
Polygon3D(const Point3D & point, const Vector3D &, const Vector3D &);
void shift_X(double dX);
void shift_Y(double dY);
void shift_Z(double dZ);
void shift(const Vector3D &);
int size() const { return points.size(); }
const Point3D & operator[] (int I) const { return points[I]; }
Point3D & operator[] (int I) { return points[I]; }
private:
QVector<Point3D> points;
};
//-------------------------------------------------------------------------------------------------
Point3D rotate_XZ(const Point3D & point, const Point3D & center, float angle);
Point3D rotate_YZ(const Point3D & point, const Point3D & center, float angle);
#endif // POINT3D_H
|
c0fe01afe95e85f63342c0a2863082a685669c02 | abb3119a35a392c5df6050fea27ad9f66da87459 | /brute_force/2798_blackJack.cpp | 8be304fd3a5e5260f8fd9a76685c19100ef515a8 | [] | no_license | SurinJo/coding_test | 0ff7875e8b6805791fb1db9ac72b6151d817d11c | e062e2219f8c7b112d310e1c2757f782981f2db4 | refs/heads/master | 2020-12-18T21:12:21.998808 | 2020-04-14T13:28:25 | 2020-04-14T13:28:25 | 235,522,505 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 676 | cpp | 2798_blackJack.cpp | #include <iostream>
#include <vector>
using namespace std;
int main(){
int n, m, temp, answer = 0;
vector<int> cards;
cin >> n >> m;
for(int i = 0; i < n; i++) {
cin >> temp;
cards.push_back(temp);
}
for(int i = 0; i < n - 2; i++) {
for(int j = i + 1; j < n -1; j++){
for(int k = j + 1; k < n; k++){
// cout << cards[i] << "," <<cards[j] << "," << cards[k] << endl;
temp = cards[i] + cards[j] +cards[k];
if(temp <= m){
answer = answer > temp ? answer : temp;
// cout << "temp: " << temp << endl;
// cout << "answe: " << answer << endl;
}
else{
// cout << "wrong" <<endl;
}
}
}
}
cout << answer;
return 0;
} |
61bac9e6f737fbb809a0baa7a303a7c2b0afffc5 | 9e4db19a93a60e35c92c99a88a572e5d6384c5c4 | /KodisoftTaskApp/ProcessMonitor.cpp | ba84b255a8572792b3a90d1153d9059471f91fbd | [] | no_license | define-rak/CodisoftTaskApp | 343c11e995518717acb707f5ab70a3fa9158b84c | af836eff9814784a6450945b3e3d2ad532b6a0bf | refs/heads/master | 2021-01-25T07:19:58.189802 | 2014-12-10T05:46:57 | 2014-12-10T05:46:57 | 27,175,700 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,902 | cpp | ProcessMonitor.cpp | #include "ProcessMonitor.h"
#include <cstdio>
ProcessMonitor::ProcessMonitor()
{
this->path = NULL;
ZeroMemory(&(this->si), sizeof(si));
si.cb = sizeof(si);
ZeroMemory(&(this->pi), sizeof(pi));
this->status = STOPPED;
this->isLoopNeeded = TRUE;
}
ProcessMonitor::ProcessMonitor(LPTSTR path)
{
this->path = new TCHAR[sizeof(path) / sizeof(TCHAR)];
lstrcpy((this->path), path);
ZeroMemory(&(this->si), sizeof(si));
si.cb = sizeof(si);
ZeroMemory(&(this->pi), sizeof(pi));
this->status = STOPPED;
this->isLoopNeeded = TRUE;
}
ProcessMonitor::ProcessMonitor(DWORD pId)
{
ZeroMemory(&(this->si), sizeof(si));
si.cb = sizeof(si);
ZeroMemory(&(this->pi), sizeof(pi));
(this->pi).dwProcessId = pId;
(this->pi).hProcess = OpenProcess(PROCESS_ALL_ACCESS, FALSE, (this->pi).dwProcessId);
if ((this->pi).hProcess != 0)
{
this->path = new TCHAR[256];
GetModuleFileNameEx((this->pi).hProcess, NULL, this->path, 256);
printf("%s", this->path);
this->status = RUNNING;
this->isLoopNeeded = TRUE;
}
else
{
this->status = STOPPED;
}
}
//
HANDLE ProcessMonitor::getProcessHandle()
{
return (this->pi).hProcess;
}
DWORD ProcessMonitor::getProcessId()
{
return (this->pi).dwProcessId;
}
DWORD ProcessMonitor::getStatus()
{
return this->status;
}
LPSTR ProcessMonitor::getPath()
{
return this->path;
}
//
BOOL ProcessMonitor::start()
{
if (this->status == STOPPED)
{
if (!CreateProcess(NULL, this->path, NULL, NULL,
FALSE, CREATE_NEW_CONSOLE, NULL, NULL, &(this->si), &(this->pi)))
{
this->status = STOPPED;
return FALSE;
}
this->status = RUNNING;
(this->log)->writeMessage(*this, "Start");
}
while (WaitForSingleObject((this->pi).hProcess, INFINITE) == WAIT_OBJECT_0)
{
(this->log)->writeMessage(*this, "Crash");
if (this->isLoopNeeded == FALSE)
{
return FALSE;
}
this->status = RESTARTING;
if (!CreateProcess(NULL, this->path, NULL, NULL,
FALSE, CREATE_NEW_CONSOLE, NULL, NULL, &(this->si), &(this->pi)))
{
this->status = STOPPED;
return TRUE;
}
else
{
this->status = RUNNING;
(this->log)->writeMessage(*this, "Start");
}
}
}
BOOL ProcessMonitor::stop()
{
if (this->status == RUNNING)
{
if (!TerminateProcess((this->pi).hProcess, EXIT_SUCCESS))
{
this->status = STOPPED;
CloseHandle(this->pi.hProcess);
CloseHandle(this->pi.hThread);
(this->log)->writeMessage(*this, "Manual shutdown");
return FALSE;
}
return TRUE;
}
return FALSE;
}
//
//
//
Logger::Logger()
{
}
Logger::Logger(std::string path)
{
this->path = path;
(this->log).open((this->path).c_str());
}
Logger::~Logger()
{
(this->path).erase();
(this->log).close();
}
//
void Logger::writeMessage(ProcessMonitor &pm, std::string action)
{
(this->log) << action.c_str() << "," << std::time(0) << "," << pm.getPath() << "," << pm.getProcessHandle() << "," << pm.getProcessId() << std::endl;
}
|
403328661e109de99a86263782d0746bc96958ba | 2945d889bec36a8be79a27ee5058366bfa7dfc32 | /src/Scene/SceneBase.h | 0b00b0c7c19a960f090d49c88c27b27450d1e6a3 | [] | no_license | peperontino39/FactoryTown | b8c35464e5866019b5e26034e32cc21b5f95d781 | 3990bb28a2d828f1b4e00f23e503e85bec97f8e8 | refs/heads/master | 2021-01-22T21:37:11.553225 | 2017-03-20T08:53:05 | 2017-03-20T08:53:05 | 85,445,646 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 977 | h | SceneBase.h | #pragma once
#include <list>
#include <memory>
#include <functional>
class GameObject;
typedef std::shared_ptr<GameObject> GameObjectRef;
class SceneBase
{
public:
virtual void onCreate();
virtual void setup();
virtual void update();
virtual void cameraDrawBegin();
virtual void lightDrawBegin();
virtual void draw();
virtual void lightDrawEnd();
virtual void nonLightDraw();
virtual void cameraDrawEnd();
virtual void drawUI();
virtual void shutdown();
virtual void mouseDown();
virtual void mouseUp();
virtual void mouseWheel();
virtual void mouseMove();
virtual void mouseDrag();
virtual void keyDown();
virtual void keyUp();
virtual void resize();
std::function<SceneBase*()> nextScene = [&]() {return nullptr; };
protected:
void create(GameObject* obj);
template<class T>
T* Instantiate(T*);
std::list<GameObject*> gameObjects;
};
template<class T>
T * SceneBase::Instantiate(T * obj)
{
gameObjects.push_back(obj);
return obj;
}
|
71ba99df8b975d288332c3804c50037d8c7f41cf | 440f814f122cfec91152f7889f1f72e2865686ce | /src/game_server/server/extension/skill/threat_event_handler.cc | 7b774db18dc7962b15e2832dba232a8f69da60ac | [] | no_license | hackerlank/buzz-server | af329efc839634d19686be2fbeb700b6562493b9 | f76de1d9718b31c95c0627fd728aba89c641eb1c | refs/heads/master | 2020-06-12T11:56:06.469620 | 2015-12-05T08:03:25 | 2015-12-05T08:03:25 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,331 | cc | threat_event_handler.cc | //
// Summary: buzz source code.
//
// Author: Tony.
// Email: tonyjobmails@gmail.com.
// Last modify: 2013-10-17 16:55:11.
// File name: threat_event_handler.cc
//
// Description:
// Define class ThreatEventHandler.
//
#include "game_server/server/extension/skill/threat_event_handler.h"
#include <boost/bind.hpp>
#include "coresh/communicator.h"
#include "game_server/server/event/game_actor_event_types.h"
#include "game_server/server/event/game_ai_event_types.h"
#include "game_server/server/event/game_event_types.h"
#include "game_server/server/extension/skill/skill_role.h"
#include "game_server/server/extension/skill/skill_role_manager.h"
namespace game {
namespace server {
namespace skill {
ThreatEventHandler::ThreatEventHandler() {}
ThreatEventHandler::~ThreatEventHandler() {}
bool ThreatEventHandler::Initialize() {
this->conn_threat_start_ = coresh::CommunicatorSingleton::GetInstance().Follow(
event::EventType::EVENT_AI_THREAT_START, coresh::Communicator::GetChannelAll(),
event::ChannelType::CHANNEL_ACTOR, boost::bind(&ThreatEventHandler::OnEventAiThreatStart,
this, _1, _2, _3, _4));
this->conn_threat_end_ = coresh::CommunicatorSingleton::GetInstance().Follow(
event::EventType::EVENT_AI_THREAT_END, coresh::Communicator::GetChannelAll(),
event::ChannelType::CHANNEL_ACTOR, boost::bind(&ThreatEventHandler::OnEventAiThreatEnd,
this, _1, _2, _3, _4));
return true;
}
void ThreatEventHandler::Finalize() {
coresh::CommunicatorSingleton::GetInstance().Unfollow(this->conn_threat_start_);
coresh::CommunicatorSingleton::GetInstance().Unfollow(this->conn_threat_end_);
}
void ThreatEventHandler::OnEventAiThreatStart(core::uint64 channel,
core::uint8 channel_type, const void *message, size_t size) {
if(message == NULL || sizeof(event::EventAiThreatStart) != size ||
channel_type != event::ChannelType::CHANNEL_ACTOR) {
LOG_ERROR("参数错误");
return ;
}
event::EventAiThreatStart *event = (event::EventAiThreatStart *)message;
// 获取 SkillRole
SkillRole *role = SkillRoleManager::GetInstance()->Get(event->threat_role_type_,
event->threat_role_id_);
if(role == NULL) {
LOG_ERROR("获取 SkillRole(%d,%lu) 失败", event->threat_role_type_,
event->threat_role_id_);
return ;
}
role->GetFightingStatus().SetStatus();
// LOG_INFO("玩家(%lu) 进入npc(%lu) 仇恨列表", event->threat_role_id_, event->npc_);
}
void ThreatEventHandler::OnEventAiThreatEnd(core::uint64 channel,
core::uint8 channel_type, const void *message, size_t size) {
if(message == NULL || sizeof(event::EventAiThreatEnd) != size ||
channel_type != event::ChannelType::CHANNEL_ACTOR) {
LOG_ERROR("参数错误");
return ;
}
event::EventAiThreatEnd *event = (event::EventAiThreatEnd *)message;
// 获取 SkillRole
SkillRole *role = SkillRoleManager::GetInstance()->Get(event->threat_role_type_,
event->threat_role_id_);
if(role == NULL) {
LOG_ERROR("获取 SkillRole(%d,%lu) 失败", event->threat_role_type_,
event->threat_role_id_);
return ;
}
role->GetFightingStatus().ResetStatus();
// LOG_INFO("玩家(%lu) 离开npc(%lu) 仇恨列表", event->threat_role_id_, event->npc_);
}
} // namespace skill
} // namespace server
} // namespace game
|
fda081acfca3875dfe171a0241caeaf766a1ac62 | 53f147359e1d136b5e66aa234d44c7dc79384e24 | /Project9/DataSource/Main.cpp | 1aa93ceff328aa601e8527c910a097979e67db88 | [] | no_license | NenadDragisic/NIKPES | c577ea44897869c98582ecc4941c227469f2c10d | df7f17d5c12e96bea365d755052284afc2fd9461 | refs/heads/master | 2021-06-07T06:15:56.108604 | 2015-12-01T19:45:31 | 2015-12-01T19:45:31 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,336 | cpp | Main.cpp | #include "stdafx.h"
#include "DataSource.h"
#include <time.h>
#include "main.h"
#include "../CommonLib/SharedFunctions.h"
DWORD WINAPI ReceiveChildren(LPVOID lpParam)
{
T_StructForhWaitForChildren *tstruct = (T_StructForhWaitForChildren*)lpParam;
tstruct->ShutdownThread = false;
int iResult = 0;
//NONBLOCKING MODE
unsigned long int nonBlockingMode = 1;
iResult = ioctlsocket(tstruct->ds->GetListenSocket(), FIONBIO, &nonBlockingMode);
if (iResult == SOCKET_ERROR)
{
printf("ioctlsocket failed with error: %ld\n", WSAGetLastError());
return 1;
}
bool socketCorrect = false;
while (true)
{
if (tstruct->ShutdownThread)
{
return 0;
}
SOCKET someSocket2 = tstruct->ds->GetListenSocket();
socketCorrect = SetNonblockingParams(someSocket2, true);
AddToArrayOfSockets(accept(someSocket2, NULL, NULL), tstruct);
}
return 0;
}
void AddToArrayOfSockets(SOCKET socket, T_StructForhWaitForChildren *tstruct)
{
int count = tstruct->count;
tstruct->sockets[count] = socket;
tstruct->count++;
}
int _tmain(int argc, _TCHAR* argv[])
{
char *port = (char*)malloc(sizeof(char)*5);
printf("Pleas enter the port: \n");
scanf("%s", port);
DWORD itForChildsID;
T_StructForhWaitForChildren *tstruct = new T_StructForhWaitForChildren();
tstruct->count = 0;
tstruct->ShutdownThread = false;
tstruct->ds = new DataSource(port);
tstruct->sockets = (SOCKET*)malloc(sizeof(SOCKET)*10);
HANDLE hWaitForChildren = CreateThread(NULL, 0, &ReceiveChildren, tstruct, 0, &itForChildsID);
char liI = getchar();
/*char *messageToSend = (char*)malloc(sizeof(char)*10);
for(int i = 0; i<10; i++)
{
messageToSend[i] = 0x41;
}*/
char *messageToSend = (char*)malloc(sizeof(char)*1024);
memset(messageToSend,'A', 1024);
char *endMessage = (char*)malloc(sizeof(char)*1024);
memset(endMessage, 'E', 1024);
/*for(int i = 0; i<100000; i++)
{
//printf("trying to send data to aggregator\n");
int sizeOfMessage = 1000008;
int iResult = 0;
iResult = SendData(sizeof(int), (char*)&sizeOfMessage, tstruct->sockets[0]);
iResult = SendData(sizeof(char) * 1000008, messageToSend, tstruct->sockets[0]);
}*/
printf("Press enter to start sending data");
liI = getchar();
while(liI!='a')
{
time_t rawtime = time(0);
struct tm *timeinfo;
time ( &rawtime );
timeinfo = localtime ( &rawtime );
printf(asctime(timeinfo));
int iResult = 0;
int sizeOfMessage = 1024;
for(int i = 0; i<102399; i++)
{
iResult = 0;
for(int j = 0; j< tstruct->count; j++)
{
iResult = SendData(sizeof(int), (char*)&sizeOfMessage, tstruct->sockets[j]);
iResult = SendData(sizeof(char) * 1024, messageToSend, tstruct->sockets[j]);
if (iResult == 0)
{
for (int k = j; k < tstruct->count; k++)
{
if (k + 1 < tstruct->count)
{
tstruct->sockets[k] = tstruct->sockets[k + 1];
}
}
j--;
tstruct->count--;
}
}
}
iResult = 0;
iResult = SendData(sizeof(int), (char*)&sizeOfMessage, tstruct->sockets[0]);
iResult = SendData(sizeof(char) * 1024, endMessage, tstruct->sockets[0]);
printf("Sending done\n");
liI = getchar();
}
liI = getchar();
tstruct->ShutdownThread = true;
Sleep(1);
CloseHandle(hWaitForChildren);
free(messageToSend);
free(endMessage);
tstruct->ds->~DataSource();
WSACleanup();
delete(tstruct);
return 0;
} |
a21b0b14bedfee5ae30c9f925d6ae45557064163 | e3c93892ce9a2f5c69d29c257ab228e16fc51a3f | /main.cpp | 641a91671cbe37998dc2e1c4a3aabba055f0c79c | [] | no_license | royallams/CPP_AdvanceTuts_Examples | 36700b90947bf2d4d374e97452733bfaf129b1bd | 105f471d47dd091ec5b53317d93546543361b9c9 | refs/heads/master | 2020-05-25T13:29:46.697544 | 2019-05-21T11:32:50 | 2019-05-21T11:32:50 | 187,824,077 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,242 | cpp | main.cpp | #include <QCoreApplication>
#include "iostream"
void T1ConstExamples();
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
T1ConstExamples();
return a.exec();
}
void T1ConstExamples()
{
/*Constantness is checked during Compile time only */
const int i = 9; //i become constant and cannot be changed
//i =6;//Shows error in compile time
const int *p1 = &i;//Data is const and pointer is not
p1 =0;// Works fine
//*p1 =0 // Shows Error in compile time
int * const p2 = 0 ; //p2 is const and not the value
const int * const p3 = 0; //data and pointer both are constant.
int const *p4 = &i;
const int *p5 = &i;// Both of the above lines are same.
std::cout<<"p1"<<"address: "<<"p1" <<"value: "<<*p1<<std::endl;
std::cout<<"p2"<<"address: "<<"p2" <<"value: "<<*p2<<std::endl;
std::cout<<"p3"<<"address: "<<"p3" <<"value: "<<*p3<<std::endl;
std::cout<<"p4"<<"address: "<<"p4" <<"value: "<<*p4<<std::endl;
std::cout<<"p5"<<"address: "<<"p5" <<"value: "<<*p5<<std::endl;
// Simply remember this rule:
//If const is on the left of the * , data is const
//If const is on the right of the * , pointer is const
}
|
e79faff548144365d67fb9106516ac3051dacff6 | 7bcabff28fa12d4187c7673f459703a1547341f1 | /Common/Error.hpp | 06bb03bd4aef0c370b671601abf9c08daafc7a60 | [] | no_license | Epitech-Tek2/arcade | d62c3ddad5249dbf6d73975f82dbbb90648765b9 | cc969f2851ba95c9c86f20f3c22acd7f360bed63 | refs/heads/master | 2023-09-01T18:31:10.063072 | 2021-10-17T12:13:42 | 2021-10-17T12:13:42 | 418,120,926 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,287 | hpp | Error.hpp | /*
** Arcade
** Sarah-Keppler
*/
#ifndef ARCADE_ERROR_HPP
#define ARCADE_ERROR_HPP
#include <string>
#include <exception>
namespace Arcade
{
class Error : std::exception
{
public:
Error(std::string const &message) noexcept;
~Error() = default;
char const *what() const noexcept;
private:
std::string const _message;
};
class FatalError : public Error
{
public:
FatalError(std::string const &message) noexcept : Error(message) {}
private:
std::string const _message;
};
class SDL2Error : public Error
{
public:
SDL2Error(std::string const &message, std::string const &sdlErr) noexcept : Error{message + ": " + sdlErr} {}
private:
std::string const message;
};
class GameError : public Error
{
public:
GameError(std::string const &message) noexcept : Error(message) {}
private:
std::string const _message;
};
class GraphicError : public Error
{
public:
GraphicError(std::string const &message) noexcept : Error(message) {}
private:
std::string const _message;
};
class MinorError : public Error
{
public:
MinorError(std::string const &message) noexcept : Error(message) {}
private:
std::string const _message;
};
}
#endif /* ARCADE_ERROR_HPP */
|
cc7f9abe524ca94867be3c626bb8548466c11b43 | dd32ac77abc3f03447e30b55a0112c146165d83c | /lib6core1/src/main/cpp/lib6core1impl1core1.cpp | cbc256623c471071e760fe1c2fe4ad7dea1761f0 | [] | no_license | big-guy/cpp-demo | 256d6a98f15317d3e9e2c57be41dfaaf1e92d5cf | 7e10e885c250a49ca0355e93a201ad9e8eeca6c1 | refs/heads/master | 2021-08-22T18:47:17.499027 | 2017-12-01T00:49:56 | 2017-12-01T00:49:56 | 112,660,596 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 567 | cpp | lib6core1impl1core1.cpp | // GENERATED SOURCE FILE
#include "lib6core1_private.h"
#include "lib6core1_impl.h"
#include <iostream>
#include <stdio.h>
/*
* Here is a function.
*/
int lib6core1impl1core11(int a, int b) {
return a + b;
}
/*
* Here is a function.
*/
int lib6core1impl1core12(int a, int b) {
return a + b;
}
/*
* Here is a function.
*/
int lib6core1impl1core13(int a, int b) {
return a + b;
}
/*
* Here is a function.
*/
int lib6core1impl1core14(int a, int b) {
return a + b;
}
/*
* Here is a function.
*/
void Lib6Core1Impl1Core1::doSomething() {
}
|
1312e6943b40a9f1911f5a864662c4d403499ac6 | dde93ce7286f5b85efb545b66e6ccc09c6e3545e | /tempmortor_pg.ino | fa47ce04307e1e5b3d08d3655d868bbb48d1470d | [] | no_license | Hirotatsu-cmd/freshman-year | f05daf6aa1fb0f821a79d699efdc095aded19261 | ab5295231a38e4d27ce66a94a8dfa1bac011c985 | refs/heads/main | 2023-01-27T15:50:41.011353 | 2020-12-11T12:40:37 | 2020-12-11T12:40:37 | 320,541,597 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 415 | ino | tempmortor_pg.ino | void setup() {
Serial.begin(115200) //通信速度
pinMode(7,OUTPUT);
}
void loop() {
int data = analogRead(0);
int i = (data,0,1023,0,5000); //取得数値を電圧に変換
int temp = map(i,300,1600,-30,100); //値を温度に
Serial.println(String(i)+"->"+String(temp));
if(temp > 23){ //23度越えで起動
digitalWrite(7,HIGH);
}else{
digitalWrite(7,LOW);
}
delay(500);
}
|
5142a30b42d4ec246ce7e98c89fab3dfb862c6b3 | edaeac7e38cffddd0c6e8addad97bd024760b853 | /DX12Programming/common/include/Model/ModelLoader.h | 7058e401136579e82669ffa4642ede1e9c8ed787 | [] | no_license | MUV38/DirectX12Training | df6b544207525ce94669ef003a000b9c8efea2eb | 6be1b17da25e61c139c78ade0434717745bd2da8 | refs/heads/master | 2023-02-08T08:53:59.555870 | 2020-08-22T15:09:52 | 2020-08-22T15:09:52 | 73,607,900 | 0 | 0 | null | 2023-02-01T09:27:59 | 2016-11-13T10:05:24 | C++ | SHIFT_JIS | C++ | false | false | 944 | h | ModelLoader.h | #pragma once
#include <d3d12.h>
#include <memory>
#include "Mesh.h"
#include "Material.h"
struct aiScene;
struct aiNode;
struct aiMesh;
struct aiMaterial;
/// モデルローダー
class ModelLoader
{
public:
ModelLoader();
~ModelLoader();
/// ロード
bool Load(ID3D12Device* device, const wchar_t* filePath);
/// ロード済みか
bool IsLoaded() const;
/// 描画
void Draw(ID3D12GraphicsCommandList* commandList);
private:
using MeshPtr = std::unique_ptr<Mesh>;
using MaterialPtr = std::unique_ptr<Material>;
private:
void ProcessNode(ID3D12Device* device, aiNode* node, const aiScene* scene);
MeshPtr ProcessMesh(ID3D12Device* device, aiMesh* mesh, const aiScene* scene);
MaterialPtr ProcessMaterial(ID3D12Device* device, aiMaterial* material, const aiScene* scene);
private:
bool m_isLoaded;
std::vector<MeshPtr> m_meshes;
std::vector<MaterialPtr> m_materials;
}; |
e5ab00445c5e48af026365d8b4847de11309565e | 9bc92c4616d4dc30918b54e99bd0ece08c77ce11 | /project/Project95/Project95/countpp2.cpp | 16c40b21faab782efc10d34ae8c0b77f7b8deb77 | [] | no_license | StasBeep/programs-CPP-Lafore | 90977d7de9291992c2454c1b93a0f38c445b2ccb | 3771c5c86f0786d77e07c5c46e2909b7c366a03b | refs/heads/main | 2023-03-19T06:52:36.182806 | 2021-03-06T00:14:09 | 2021-03-06T00:14:09 | 344,962,693 | 0 | 0 | null | null | null | null | WINDOWS-1251 | C++ | false | false | 954 | cpp | countpp2.cpp | // countpp2.cpp
// операция ++, возвращающий значения
#include <iostream>
using namespace std;
// ----- class Counter ----------------------------------------
class Counter
{
private:
unsigned int count; // значение счётчика
public:
Counter() : count(0) // конструктор
{ }
unsigned int get_count() // получить значение
{
return count;
}
Counter operator++() // увеличить значение
{
++count;
Counter temp;
temp.count = count;
return temp;
}
};
// ----- int main() -------------------------------------------
int main()
{
Counter c1, c2; // определение переменных
cout << "\nc1 = " << c1.get_count(); // вывод на экран
cout << "\nc2 = " << c2.get_count();
++c1;
c2 = ++c1;
cout << "\nc1 = " << c1.get_count(); // снова показываем
cout << "\nc2 = " << c2.get_count() << endl;
return 0;
} |
1a3811506ca2dc2e9715ecaeaede24808fa92103 | 28870fb92257576afc06de0cb61ad4ee2e5efe40 | /174.Dungeon Game.cpp | 223ccf47fc360db3ef89c75b4bbf2ef42da7d44a | [] | no_license | roddykou/Leetcode | f1de8198c349baa5a4e51da48d1b7d6e6a872167 | 708e54c03a7125dded838539272ad0251a97f793 | refs/heads/master | 2021-03-12T22:28:59.459979 | 2016-10-28T19:19:54 | 2016-10-28T19:19:54 | 40,782,721 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 744 | cpp | 174.Dungeon Game.cpp | #include <iostream>
#include <vector>
using namespace std;
int calculateMinimumHP(vector<vector<int>>& dungeon) {
int row = dungeon.size(), col = dungeon[0].size();
vector<vector<int> > dp (row, vector<int> (col, 0));
dp[row - 1][col - 1] = max(1, 1 - dungeon[row - 1][col - 1]);
for (int i = row - 2; i >= 0; i--)
dp[i][col - 1] = max(1, dp[i + 1][col - 1] - dungeon[i][col - 1]);
for (int j = col - 2; j >= 0; j--)
dp[row - 1][j] = max(1, dp[row - 1][j + 1] - dungeon[row - 1][j]);
for (int i = row - 2; i >= 0; i--) {
for (int j = col - 2; j >= 0; j--) {
dp[i][j] = max(1, min(dp[i + 1][j], dp[i][j + 1]) - dungeon[i][j]);
}
}
return dp[0][0];
}
int main() {
}
|
719cc70e9c5342f630b0cd1dc4bdfe3d39210988 | 430367f2418f52697171bfe7f319b104f64c78fe | /shell/src/shell.hpp | 18b2927bba14eff3e5c35a875a77d3969646841b | [] | no_license | sherwinp/zx | 93277431aebec16c00342f66c8174dd95a66a153 | 7ac5c806b8c05eef3d6e2bf1c6075d90d3d1dd8c | refs/heads/master | 2020-03-17T15:49:17.160480 | 2018-05-17T03:56:45 | 2018-05-17T03:56:45 | 133,725,353 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 180 | hpp | shell.hpp | #ifndef SHELL_H
#define SHELL_H
#include <epoxy/gl.h>
#include <GLFW/glfw3.h>
#include <iostream>
using namespace std;
using std::cout;
using std::endl;
using std::ios;
#endif
|
8f12c3bf11c81313b243c6daa6e661b258bfac9a | e4b698751866d8f9834c4bb67aa9b576c4ac8fef | /memoryTests/src/benchmark/02.cpp | 04086c2f15f41af3b119de042a6a2223613d4e27 | [] | no_license | MultiTeemer/SandboxTester | 4e6414ea43ba96bcdf9fbc679bedd62b4925059c | 3a9bafc1e4125cb399a58ecabdf03eb1a255f673 | refs/heads/master | 2021-01-17T13:24:56.183830 | 2015-05-25T05:17:36 | 2015-05-25T05:17:36 | 25,192,363 | 1 | 1 | null | 2016-06-18T11:07:49 | 2014-10-14T06:02:30 | Ruby | UTF-8 | C++ | false | false | 101 | cpp | 02.cpp | #include <ctime>
int main()
{
clock_t goal = 500 + clock();
while (goal > clock());
return 0;
} |
eaffd78abfcc3a3aecc0ccfa6ee94beeaf609c40 | ec48b95c78cc63471cc2fe26a33d7927dfc652b9 | /SettingsScreen.h | 020ee1d36daf1630f2ba66f36018f28e9fdda850 | [] | no_license | emilekm2142/AllWatch_SSD1306 | 59321cfa685f74ff05414cf94b9e37ce5cf48d2c | 91e5a3b0235ecf6ff30f551627427f5ef0751207 | refs/heads/master | 2021-07-18T02:20:31.575471 | 2019-08-15T17:47:26 | 2019-08-15T17:47:26 | 177,471,950 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,405 | h | SettingsScreen.h | // SettingsScreen.h
#ifndef _SETTINGSSCREEN_h
#define _SETTINGSSCREEN_h
#if defined(ARDUINO) && ARDUINO >= 100
#include "arduino.h"
#else
#include "WProgram.h"
#endif
#include "LinkedList.h"
#include "Layout.h"
#include "Widget.h"
#include "SettingsManager.h"
#include "Animation.h"
#include "UserInterface.h"
#include "StaticResources.h"
#include "CustomScreen.h"
class SettingsScreen:public CustomScreen
{
protected:
int offset = 15;
public:
UserInterfaceClass* UI;
SettingsManager* sm;
SettingsScreen(UserInterfaceClass*& UI, SettingsManager*& sm) {
this->UI = UI;
this->sm = sm;
}
virtual void Back(Renderer& r) override {
sm->CloseSettings();
Serial.println("back");
UserInterface.ReturnToParentLayout();
}
virtual void Ok(Renderer& r) override {
}
virtual void Down(Renderer& r) override {
auto a = new Animation(this->offset, offset - 10, 50, -1);
UI->RegisterAnimation(a);
}
virtual void Up(Renderer& r) override {
auto a = new Animation(this->offset,offset+ 10, 50, 1);
UI->RegisterAnimation(a);
}
virtual void Draw(Renderer& r) override{
r.DrawAlignedString(GlobalX + 0, GlobalY + offset, "Connect to WiFi 'test', password '123456789'. Open any browser and type 192.168.4.1 \n Press Back to cancel", r.GetScreenWidth(), r.Left);
}
virtual void OnGetInFocus(Renderer& r) override {
offset = 15;
}
};
#endif
|
ee52ff0f537b6acacb6fac262fca3faa419385ea | 211838c5c28a613ac0dda72c56c595d734f88f66 | /rob/main/led_arc_board.h | 6ac4cf0c9459df335efd489a8a0a2a2eafee73f9 | [] | no_license | astrocfi/civ-explorers | f7be05dd416de30b63323270b80415cbbdae6918 | cbae77f55b1ab4debb5a544fb641650956baab77 | refs/heads/master | 2023-04-09T15:54:30.361414 | 2021-04-20T17:43:31 | 2021-04-20T17:43:31 | 344,970,912 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,943 | h | led_arc_board.h | /*******************************************************************************
* The LEDArcBoad class
*
* This class defines the interface for the serial LED Arc Board. There can
* be a single board with 8 LEDs, or two boards with 16 LEDs. The LEDs are
* RGB. The basic functionality is to draw an arc of LEDs from the lowest
* value to the high value. Optionally the moving average and/or peak value
* can be displayed automatically.
*
* Author: Robert S. French <rfrench@rfrench.org>
* Derived from work by John Rowling
*
* This work is licensed under the Creative Commons Attribution-NonCommercial
* 4.0 International License. To view a copy of this license, visit
* http://creativecommons.org/licenses/by-nc/4.0/ or send a letter to Creative
* Commons, PO Box 1866, Mountain View, CA 94042, USA.
******************************************************************************/
#ifndef __LEDARC_ARC_BOARD_H__
#define __LEDARC_ARC_BOARD_H__
#include <Arduino.h>
#define LEDARC_PWM_PIN 9
#define LEDARC_STORE_PIN 7
#define LEDARC_CLOCK_PIN 8
#define LEDARC_DATA_PIN 6
#define LEDARC_DEFAULT_PWM 240 // 0-255, higher is dimmer
// When moving the arc to a higher or lower value, optionally the arc can move
// one LED at a time to make it look smoother. If this feature is enabled, this
// is the delay between adjacent LEDs.
#define LEDARC_DEFAULT_ARC_SMOOTHING_SPEED 20 // ms
// If enabled, a moving average is calculated at a regular interval based on
// the current arc value. This is the delay between samples used to compute the
// moving average.
#define LEDARC_DEFAULT_MOVING_AVERAGE_SPEED 100 // ms
// The moving average is calculated by keeping samples in a round-robin buffer.
// This is the maximum and default number of samples to keep. The moving average
// is calculated over a time period of
// LEDARC_DEFAULT_MOVING_AVERAGE_SPEED * LEDARC_MAX_AVERAGE_HISTORY
#define LEDARC_MAX_AVERAGE_HISTORY 20 // Samples @ given interval
#define LEDARC_DEFAULT_AVERAGE_HISTORY 20 // Samples @ given interval
// If enabled, a "sticky" peak value is stored and displayed for the given
// amount of time. If the arc value increases, the peak value is set to the new
// value, but if the arc value decreases, the old peak value is maintained.
// After the time has elapsed, the peak value is forgotten and a new peak is
// stored.
#define LEDARC_DEFAULT_PEAK_TTL 4000 // ms
class LEDArcBoard
{
public:
// The id is purely for external use if you need to identify which instance
// of the class you're looking at. It is not currently used for anything
// else.
// The bool arguments say whether or not to turn on the given feature.
// These can be changed in the future with the methods below.
LEDArcBoard(byte id,
bool enable_moving_average=true,
bool enable_peak=true,
bool smooth_arc=true);
byte get_id();
byte set_id(byte id);
// Initialize operation. Must be called before calling update_leds the
// first time.
void begin();
// Update the LEDs with the current value (and moving average and peak).
// Until this is called nothing changes on the hardware. This method
// should be called as often as possible. If the proper time hasn't elapsed,
// nothing will be done.
void update_leds();
// Set the current value to display on the arc. This value is in "source
// units", which will be mapped later in some manner to the particular LED
// positions.
void set_current_val(int16_t cur_val);
int16_t get_current_val();
// Change the LED brightness (0-255). Higher values are dimmer.
void set_led_brightness(byte pwm);
byte get_led_brightness();
// Arc smoothing gradually adds/removes one LED at a time when the displayed
// value changes.
void enable_arc_smoothing();
void disable_arc_smoothing();
void set_arc_smoothing_speed(unsigned long);
unsigned long get_arc_smoothing_speed();
// The moving average calculates the average and displays it as a special
// color. See comments above for details.
void enable_moving_average();
void disable_moving_average();
void set_moving_average_size(uint16_t size);
uint16_t get_moving_average_size();
void set_moving_average_speed(unsigned long);
unsigned long get_moving_average_speed();
// The peak displays a "sticky" peak value which eventually disappears.
// See comments above for details.
void enable_peak();
void disable_peak();
void set_peak_ttl(unsigned long ttl);
unsigned long get_peak_ttl();
private:
byte _convert_val_to_index(int16_t val);
byte _id; // Unique ID of this board
int16_t _cur_val; // The most recently set value to display
byte _displayed_index; // The index of the highest LED actually displayed
bool _smooth_arc; // True if we want to smooth out changes in the arc
unsigned long _arc_smoothing_speed; // Number of ms between arc changes
unsigned long _last_led_update_time; // The time of the last arc update
byte _brightness; // The PWM of the LEDs
byte _last_brightness; // So we don't update the pin unnecessarily
bool _ave_enabled; // True if we want to keep a moving average
byte _ave_val_history[LEDARC_MAX_AVERAGE_HISTORY]; // Round robin buffer
uint16_t _ave_history_pos; // Position in buffer
uint16_t _ave_history_size; // How much of the buffer we actually want to use
unsigned long _ave_speed; // Number of ms between updates to the buffer
unsigned long _last_ave_time; // The time of the last buffer update
bool _peak_enabled; // True if we want to have a maximum-value LED
byte _peak_index; // The index of the peak LED
unsigned long _peak_ttl; // How long the peak LED stays lit (ms)
unsigned long _last_peak_update_time; // The time of the last update of the peak LED
};
#endif // __LEDARC_ARC_BOARD_H__
|
a4019f4db716f2ddff2b8743013008de470ca0f5 | e3886c61efedde58d4f14a347684697cbb57a45d | /SLAM10-last/src/dense_mapping.cpp | b08e26ed29e70a731fbc605e0e82a996a2f12620 | [] | no_license | gtkansy/VSLAM-tutorial | 0a81c4982acab1f54448ff7f5365f1b6c31cf303 | e7fa0d6e04c18c9b9ead967c3d73bf059137fc4e | refs/heads/master | 2020-03-27T08:15:20.654973 | 2018-08-27T02:29:40 | 2018-08-27T02:29:40 | 146,236,994 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 278 | cpp | dense_mapping.cpp | //
// Created by gtkansy on 18-7-24.
//
#include <iostream>
#include <vector>
#include <fstream>
using namespace std;
#include <sophus/se3.hpp>
using namespace Sophus;
int main(int argc,char** argv){
if(argc!=2){
cout<<"path"<<endl;
return -1;
}
} |
71ff7da0195222b2db09b4bdce5b1411b52e3085 | 087543eee8b84c79c4dc2863150fcced168be0ea | /Level 3/Operations avancees sur les chaines de caracteres/Dechiffrement de la premiere page/main.cpp | 38c736108d5171bc5d844432eb630388ff260315 | [
"MIT"
] | permissive | zied-ati/France-ioi | 42955296001c932c8781431f5c34d3f12d743412 | 6db69e67fcb5cf34fed6c5e685d2a9018eec3e7a | refs/heads/master | 2022-03-27T23:26:16.336482 | 2020-01-06T15:36:56 | 2020-01-06T15:36:56 | 75,761,623 | 35 | 34 | MIT | 2020-01-06T15:36:58 | 2016-12-06T18:57:27 | C++ | UTF-8 | C++ | false | false | 549 | cpp | main.cpp | #include <bits/stdc++.h>
#define N 26
using namespace std;
string s,t,s1,s2;
int n;
int tab[N];
int main()
{
ios_base::sync_with_stdio(0);
cin.tie(0);
getline(cin,s);
for(unsigned int i=0;i<s.length();++i)
{
tab[i]=s[i]-'a';
}
getline(cin,t);
for(unsigned int i=0;i<t.length();++i)
{
if(t[i]>='a' && t[i]<='z')
cout<<char(tab[t[i]-'a']+'a');
else if(t[i]>='A' && t[i]<='Z')
cout<<char(tab[t[i]-'A']+'A');
else
cout<<t[i];
}
cout<<endl;
return 0;
}
|
11b3de33ad994d9ad5e950aae68fb1075bc756a4 | 8d62f7f03637b74953f6ed02da6ac8151e9373a0 | /include/main.hpp | 69ea681a90ed7a5752367d3b9c032c6f63ba8c9e | [] | no_license | xrex110/voronoi-diagram | b5c2806a4b132a0dd0b7f563a262701882118d48 | 73766262bb7a4b7b1a39835d9c889d394600c576 | refs/heads/master | 2022-12-02T12:20:34.430325 | 2020-08-21T06:59:22 | 2020-08-21T06:59:22 | 288,021,858 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 939 | hpp | main.hpp | #ifndef MAIN_H
#define MAIN_H
#include "geom.hpp"
void createWindow(int width, int height, std::vector<Point> sites, std::vector<Triangle> triangles, std::vector<Cell> voronoi);
std::vector<Point> randomPoints(int width, int height, int num_points);
void DrawTriangle(SDL_Renderer* renderer, Triangle tri);
void DrawCircle(SDL_Renderer * renderer, int centreX, int centreY, int radius);
void DrawCell(SDL_Renderer* renderer, Cell cell);
std::vector<Triangle> delauney(std::vector<Point> sites);
bool verifyDelauney(std::vector<Point> sites, std::vector<Triangle> triangles);
template <class T> void printVector(std::vector<T> &vec);
template <typename T> bool vectorSetInsert(std::vector<T>& vec, T elem);
bool rigorDelauney(int rangeX, int rangeY, int numPoints, int numRuns, bool verbose);
std::vector<Cell> delauneyToVoronoi(std::vector<Point> sites, std::vector<Triangle> triangles);
void presentWindow();
#endif |
64117dd5c48c6264f84f94da5c3596455ae0f062 | 27c917a12edbfd2dba4f6ce3b09aa2e3664d3bb1 | /LeetCode/30Days_May_LeetCoding_Challenge/19.cpp | 42c93b6e69b4a9c278e179452838ba48a1ab87d0 | [] | no_license | Spetsnaz-Dev/CPP | 681ba9be0968400e00b5b2cb9b52713f947c66f8 | 88991e3b7164dd943c4c92784d6d98a3c9689653 | refs/heads/master | 2023-06-24T05:32:30.087866 | 2021-07-15T19:33:02 | 2021-07-15T19:33:02 | 193,662,717 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,088 | cpp | 19.cpp | // Online Stock Spanner
// Method 1
class StockSpanner {
public:
vector<int> prices, res;
StockSpanner() {
// prices.clear();
// res.clear();
}
int next(int price) {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
int ans = 1;
for(int i=res.size()-1; i>=0; i--)
{
if(prices[i] <= price)
{
ans += res[i];
i -= res[i]; //jump to the location till when price is surely lower than current price
++i;
}
else
break;
}
prices.push_back(price);
res.push_back(ans);
return ans;
}
};
// Method 2
class StockSpanner {
public:
stack<pair<int, int>> s;
StockSpanner() {}
int next(int price) {
int res = 1;
while (!s.empty() && s.top().first <= price) {
res += s.top().second;
cout<<s.top().first<<" ";
s.pop();
}
s.push({price, res});
return res;
}
}; |
2b4a77745b4f34b7c25d6491c6ece046462950f4 | 1cc288f731ebce6a914e30d9aadeaa5610758b5c | /Etrocenter/DlgAddModifyRecTime.h | 361f6d54eddc1845e440f90f55d1c9c96e8d8cd1 | [] | no_license | dong777/eNVR | 3a14bbfb4a1b4c13b5c4d7fe1dcb67434d6970c1 | 7bdb4825188a029865fd4c6657d3ebab1b5486f5 | refs/heads/master | 2021-01-19T18:25:47.645426 | 2014-08-03T10:00:21 | 2014-08-03T10:00:21 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,328 | h | DlgAddModifyRecTime.h | #pragma once
#include "afxwin.h"
#include "afxdtctl.h"
#include "resource.h"
#include "BaseDialog.h"
#include "INI.h"
struct RecTimeInfo
{
TCHAR cDayType[30];
TCHAR cDate[30];
TCHAR cTimeFrom[30];
TCHAR cTimeTo[30];
};
// CDlgAddModifyRecTime dialog
class CDlgAddModifyRecTime : public CDialog
{
DECLARE_DYNAMIC(CDlgAddModifyRecTime)
public:
CDlgAddModifyRecTime(CWnd* pParent = NULL); // standard constructor
virtual ~CDlgAddModifyRecTime();
afx_msg HBRUSH OnCtlColor(CDC* pDC, CWnd* pWnd, UINT nCtlColor);
afx_msg BOOL OnEraseBkgnd(CDC* pDC);
CBrush m_SilverBrush;
CBrush m_WhiteBrush;
// Dialog Data
enum { IDD = IDD_DLG_REC_TIME_ADD_MODIFY };
protected:
virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support
DECLARE_MESSAGE_MAP()
CComboBox pDayTypeCombo;
CDateTimeCtrl pDatePicker;
CDateTimeCtrl pTimeFromPicker;
CDateTimeCtrl pTimeToPicker;
CDatabase* pDB;
CString csDSN, csDBUser, csDBPass, csODBC; //For Database
bool EditFlag;
CString m_csDayType, m_csDate, m_csTimeFrom, m_csTimeTo;
public:
RecTimeInfo m_RecTimeInfo;
/*void vDBConnect();
void vDBClose();*/
virtual BOOL OnInitDialog();
void vSetScheduleTime(CString csDayType, CString csDate, CString csTimeFrom, CString csTimeTo);
afx_msg void OnCbnSelchangeComboDayType();
afx_msg void OnBnClickedOk();
};
|
b5b37e7ab2ec958cfe6570a2539fc66f397a14be | 38cad08afe9830c2258b9659044faa22d709d16d | /capp.h | eb006c56ae9881bc4275c846f13cd9555e6ce5a8 | [] | no_license | jiacheng2012/311_tester | 911d8138986531821db113032c7421f4abb95fe9 | 0df92063b7f8adb43074da7a2586bb01cc116bb1 | refs/heads/master | 2021-01-25T10:29:57.911014 | 2013-02-05T09:07:49 | 2013-02-05T09:07:49 | 7,988,954 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 3,152 | h | capp.h | #ifndef CAPP_H
#define CAPP_H
#include <QtGui>
#include <QApplication>
#include <QtCore/QCoreApplication>
#include <QTextStream>
#include <QtDebug>
#include <QVariant>
#include "configure/cconfig.h"
#include "database/cdatabase.h"
#include "database/cuser.h"
#include "interface/cmainwindow.h"
#include "processing/cmeter.h"
#include "processing/cconfigjob.h"
class CApp : public QApplication
{
Q_OBJECT
public:
CApp(int& argc, char* argv[]);
~CApp();
void addTestJobFromID(QString);
void sleep(quint32 msec);
void startJob();
void deleteJob();
qint64 isRunning();
public:
CConfig *_config;
CDatabase *_db;
CUser *_user;
CTestJob *_tjob;
CMeter *_meter;
QSharedMemory *_appMemory;
signals:
void updateTestJobSetting();
void newMessage(QString,bool);
void _232SetupFullTest();
void _232SetupAdjustTest();
void _232SetupFunctionTest();
void _485SetupFullTest();
void _485SetupAdjustTest();
void _485SetupFunctionTest();
void databaseSetup();
void jobSetup(QString,QString,QString);
void stop232();
void stop485();
void sendBackFullTestData_key(QByteArray);
void sendBackFullTestData_led(QByteArray);
void sendBackAdjustTestData_speed(CDataFrame);
void sendBackFullTestData_freq_232(QByteArray);
void sendBackFullTestData_ioi_232(QByteArray);
void sendBackFullTestData_ioo_232(QByteArray);
void sendBackFullTestData_analog_232(QByteArray);
void sendBackFullTestData_lcdbacklight(QByteArray);
void sendBackFullTestData_can_232(QByteArray);
void sendBackFullTestData_freq_485(QByteArray);
void sendBackFullTestData_ioi_485(QByteArray);
void sendBackFullTestData_ioo_485(QByteArray);
void sendBackFullTestData_analog_485(QByteArray);
void sendBackFullTestData_can_485(QByteArray);
void sendBackAdjustTestData_watertemp(CDataFrame);
void sendBackAdjustTestData_oil(CDataFrame);
void sendBackAdjustTestData_rotate(CDataFrame);
void sendBackFullTestData_memory(QByteArray);
void sendBackFullTestData_selfpower(QByteArray);
void sendBackFullTestData_metervoltage232(QByteArray);
void sendBackFullTestData_metervoltage485(QByteArray);
void sendBackAdjustTestData_analog_485(QByteArray);
void sendBackAdjustTestData_analog_232(CDataFrame);
void sendBackFunctionTestData_232(CDataFrame);
void toTestTabPage(int);
private:
QMutex _mutex;
public slots:
void addUser(CUser&);
};
#endif // APP_H
|
8e77ac4b576356207b961ad258c98d92f3d27fcb | 8cd96546d61c821b8c57a4c4b97f5d00efd1ef31 | /P05_Scoring/source/PlotPixl.CC | 417a499c55de792bb7e8eb6723b97eae0ce85cb5 | [
"BSD-2-Clause"
] | permissive | koichi-murakami/g4tutorial2018 | bf862ca7876d47b8c87aa53969f317de0ead42da | ff02a097d83fe070257926360b5a39ffcd487a30 | refs/heads/master | 2020-03-21T17:02:38.877540 | 2018-09-10T08:46:30 | 2018-09-10T08:46:30 | 138,809,618 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 168 | cc | PlotPixl.CC | {
gROOT->Reset();
TFile *f = TFile::Open("Pixel.root");
TH2D* wxy = (TH2D*)f->Get("1");
wxy->Draw("HIST");
wxy->Draw("BOX");
wxy->Draw("SURF");
wxy->Draw("SURF2");
}
|
3e0fe6232fb6ffa46c472649f2818ce516206de5 | d508027427b9a11a6bab0722479ee8d7b7eda72b | /utils/ATOM_studio/model_plugin/model_prop_editor.h | 76c2b6bf677378aad28a137abc20c5caf0f0a604 | [] | no_license | gaoyakun/atom3d | 421bc029ee005f501e0adb6daed778662eb73bac | 129adf3ceca175faa8acf715c05e3c8f099399fe | refs/heads/master | 2021-01-10T18:28:50.562540 | 2019-12-06T13:17:00 | 2019-12-06T13:17:00 | 56,327,530 | 5 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,031 | h | model_prop_editor.h | #ifndef __ATOM3D_STUDIO_MODEL_PROP_EDITOR_H
#define __ATOM3D_STUDIO_MODEL_PROP_EDITOR_H
#if _MSC_VER > 1000
# pragma once
#endif
class AS_Editor;
class ModelPropCommandCallback;
class MyValueChangeCallback;
class ModelPropEditor
{
public:
ModelPropEditor (AS_Editor *editor);
~ModelPropEditor (void);
public:
void setPosition (int x, int y, int w, int h);
void show (bool b);
bool isShown (void) const;
void refresh (void);
void setModel (ATOM_Geode *model);
ATOMX_TweakBar *getBar (void) const;
AS_Editor *getEditor (void) const;
void setParamChanged (bool b);
void updateTime (void);
void setCurrentMesh (int currentMesh);
int getCurrentMesh (void) const;
ATOM_Geode *getModel (void) const;
void setModified (bool b);
bool isModified (void) const;
void setReadonly (bool readonly);
private:
void createBar (void);
void setupBar (void);
void newParameter (const char *name, ATOM_ParameterTable::ValueHandle value);
void newFloatParameter (const char *name, float value);
void newIntParameter (const char *name, int value);
void newVectorParameter (const char *name, const ATOM_Vector4f &value);
void newColorParameter (const char *name, const ATOM_Vector4f &value);
void newDirectionParameter (const char *name, const ATOM_Vector4f &value);
void newBoolParameter (const char *name, bool value);
void newEnumParameter (const char *name, const ATOM_VECTOR<ATOM_STRING> &enumNames, const ATOM_VECTOR<int> &enumValues, int value);
void newTextureParameter (const char *name, const char *filename);
private:
ATOM_AUTOREF(ATOM_Geode) _model;
AS_Editor *_editor;
ATOMX_TweakBar *_bar;
MyValueChangeCallback *_valueCallback;
int _currentMesh;
bool _isShown;
bool _modified;
ModelPropCommandCallback *_callback;
};
class ModelPropCommandCallback: public ATOMX_TweakBar::CommandCallback
{
public:
ModelPropEditor *_editor;
ModelPropCommandCallback (ModelPropEditor *editor): _editor(editor)
{
}
void callback (ATOMX_TWCommandEvent *event);
};
#endif // __ATOM3D_STUDIO_MODEL_PROP_EDITOR_H
|
9f93655d81f2a90f8a9c72e8b4a74005b0100a7c | b0124b7d41a1e0d8bb71cc52bd35ffa6cc854778 | /Code Arduino/Projet.ino | c2780b8756964bf1a74f67ea268a03d70d20edc1 | [] | no_license | TheoGaschard/Projet-plante-connectee | 5188b6f1d36d851ddd1d80f3641c2ac6a3c5b40e | e8a9878a3ddf53c9bebeca1da150641d24e3a7d1 | refs/heads/master | 2022-07-19T04:39:22.092841 | 2019-06-28T10:17:51 | 2019-06-28T10:17:51 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,696 | ino | Projet.ino | /*
Program for the "projet plante conectée".
*/
#define _DEBUG_
#define _DISABLE_TLS_
#include <DHT.h> // Add of the DHT library.
#include <DHT_U.h> // Add of the DHT_U library.
#include <WiFi.h>
#include <ThingerWifi.h> // Adding the wi-fi library.
#include "Wire.h"
#include <Sparkfun_APDS9301_Library.h> // Adding the light sensor library.
#define THINGER_USE_STATIC_MEMORY
#define THINGER_STATIC_MEMORY_SIZE 512
#define MOISTURE_PIN A4 //PIN connected to the SEN0193 sensor.
#define DHTPIN A2 // PIN connected to the DHT11 sensor.
#define LIGHT_PIN 2 // Pin linked to the APDS9301 light sensor.
// We define the connection options.
#define USERNAME "username"
#define DEVICE_ID "arduino"
#define DEVICE_CREDENTIAL "r5Boe1Ige&#j"
#define SSID "XperiaXA2" // Name of the wi-fi network.
#define SSID_PASSWORD "123456" // Password of the wi-fi network.
ThingerWifi thing(USERNAME, DEVICE_ID, DEVICE_CREDENTIAL); // Establishing connection with the wi-fi network.
APDS9301 apds;
int moistureValue = 0;
int humidityValue = 0;
int temperatureValue = 0;
int luminosityValue = 0;
DHT dht(DHTPIN, DHT11);
void setup(){
pinMode(MOISTURE_PIN, INPUT);
dht.begin();
thing.add_wifi(SSID, SSID_PASSWORD); // Configure the wi-fi network.
delay(50); // The CCS811 wants a brief delay after startup.
Serial.begin(115200); // Open the serial monitor.
Wire.begin();
// APDS9301 sensor setup.
apds.begin(0x39);
apds.setLowThreshold(0); // Sets the low threshold to 0, effectively
// disabling the low side interrupt.
apds.setHighThreshold(50); // Sets the high threshold to 500. This
// is an arbitrary number I pulled out of thin
// air for purposes of the example. When the CH0
// reading exceeds this level, an interrupt will
// be issued on the INT pin.
apds.enableInterrupt(APDS9301::INT_ON); // Enable the interrupt.
apds.clearIntFlag();
// Interrupt setup.
pinMode(LIGHT_PIN, INPUT_PULLUP);
Serial.println(apds.getLowThreshold());
Serial.println(apds.getHighThreshold());
thing["humidity"] >> humidityValue;
thing["moisture"] >> moistureValue;
thing["temperature"] >> temperatureValue;
thing["luminosity"] >> luminosityValue;
}
void loop()
{
moistureValue = analogRead(MOISTURE_PIN); // We collect the moisture of the dirt.
humidityValue = dht.readHumidity(); // We collect the humidity of the air.
temperatureValue = dht.readTemperature(); // We collect the temperature of the air.
luminosityValue = apds.readCH0Level(); // We collect the luminosity.
thing.handle();
apds.clearIntFlag();
delay(1000);
}
|
d688494e9695d8c11f5a7c12945c71bb58066850 | 429d24a2be40775620f7aebd962fa624ca15c3f7 | /main.cpp | 4876123a03377ec6828184d4606f5ee0a2135c13 | [] | no_license | Jiang5/LCS | ec2c62d06f137623cdf95f9558320485a37789b6 | 3c4c839fcf5a923e79bba4add0d89fb4f58368a7 | refs/heads/master | 2021-01-21T06:42:45.145272 | 2017-02-27T05:43:31 | 2017-02-27T05:43:31 | 83,272,560 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,159 | cpp | main.cpp | #include <iostream>
#include <fstream>
#include <string>
using namespace std;
string a, b, subL;
int totalL = 0;
int max(int a, int b){
if(a >= b) return a;
return b;
}
//LCS Alg
void lcs(string a, string b){
int m, n;
m = a.length();
n = b.length();
int length[m+1][n+1];
for(int i = m; i >= 0; i--){
for(int j = n; j >= 0; j--){
if(i == m || j == n) length[i][j] = 0;
else if(a[i] == b[j]) length[i][j] = length[i+1][j+1] + 1;
else length[i][j] = max(length[i+1][j], length[i][j+1]);
}
}
totalL = length[0][0];
int i = 0, j = 0;
while(i < m && j < n){
if(a[i] == b[j]){
subL.push_back(a[i]);
i++;
j++;
}
else if(length[i+1][j] >= length[i][j+1]) i++;
else j++;
}
}
int main(){
//read file
ifstream myfile("input.txt");
myfile >> a;
myfile.ignore(1000, '\n');
myfile >> b;
myfile.close();
lcs(a, b);
//write to file
ofstream myfile1("output.txt");
myfile1 << totalL << endl;
myfile1 << subL << endl;
myfile1.close();
return 0;
}
|
aa10e993a51021dc550017e196d51a640be3e2d6 | a048f5b844b36576e21d4fc5866ecf8167da6a45 | /Lexer/LexerImplementation.h | b8d4aa283660a2348225615fcc0090a101875222 | [
"Apache-2.0"
] | permissive | dillu24/MiniLang_Compiler | e5106f6a4a09dae51c08bd02bdfa9a69467754ef | 13a3e9ab3ca33d9658fd5063ced5c6ce98e6dc04 | refs/heads/master | 2021-04-15T07:26:02.984098 | 2018-07-27T10:40:41 | 2018-07-27T10:40:41 | 126,584,856 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,429 | h | LexerImplementation.h | //
// Created by Dylan Galea on 14/03/2018.
//
#ifndef COMPILERSASSIGNMENT_LEXER_H
#define COMPILERSASSIGNMENT_LEXER_H
#include <iostream>
#include <fstream>
#include <vector>
#include "Token.h"
#include "State.h"
using namespace std;
/**
* This class is used to implement the lexer and get the next token within the source code program.
*/
namespace Lexer{
class LexerImplementation {
public:
/**
* This constructor is used to initialize the lexer fields and set the current state to S0(the first state
* in the DFSA) . Also it reads the default file SourceCodeInput , supplied in this directory.
*/
LexerImplementation();
/**
* This constructor is used to initialize the lexer fields and set the current state to S0(the first state in
* the DFSA) . However the different from the other constructor is that this reads from any file path supplied
* in the file_name parameter
* @param file_name
* Stores the file path the lexer is to read from
*/
explicit LexerImplementation(string file_name);
~LexerImplementation(); //default destructer
/**
* This method is used to get the next token that the lexer has identified
* @return
* A pointer to the next token the lexer has identified
*/
Token* getNextToken();
/**
* This method is used to give the character array the string to be tokenized .. this is mostly used by the REPL
* @param input
* Stores the input to be parsed into characters
*/
void initializeCharactersWithString(string input);
/**
* This method is used by the interpreter in interective mode to clear the characters that have been inputted
* in the console.
*/
void clearCharactersContainer();
/**
* This method is used by the REPL in order to start reading again from the first character of the vector of characters
*/
void restartCurrentInputIndex();
/**
* This method initialized the list of characters in the source input program supplied as parameter
* @param file_name
* Stores the path the lexer is to read from as input program
*/
void initialize_input_characters(string file_name);
private:
int lineNumber; // This stores the line number the lexer is in , in order to report lexing errors
vector<char> input_characters; // stores the characters identified in the input file
int current_input_index; //stores the current index the lexer is in in order to read the next character
State current_state; // Stores the current state in the DFSA the lexer is in
/**
* This is a function that determines the next state in the DFSA depending on the state the lexer is currently
* in , and the input character the lexer has read . Note that we have implemented a table driven lexer , however
* the table was not defined as an actual 2D array in order not to have 0(n^2) memory saved , however this was
* implemented as a switch case statements
* @param state
* Stores the state the lexer is currently in
* @param input
* Stores the input character evaluated from the source program
* @return
* The next state to go to.
*/
State transitionFunction(State state,char input);
/**
* This method check if the current state is a final state
* @return
* True if final state
* False if no
*/
bool checkIfFinalState();
/**
* This method checks if 'c' is a binary operator . Note that '-' in this language can be also a negation symbol
* thus it was not considered in this method
* @param c
* The character to be evaluated
* @return
* True if Binary Operator
* False if not a Binary Operator
*/
bool isBinaryOperator(char c);
/**
* This method checks if 'c' is a punctuation symbol
* @param c
* The character to be evaluated
* @return
* True if punctutation symbol
* False if not punctuation symbol
*/
bool isPunct(char c);
};
}
#endif //COMPILERSASSIGNMENT_LEXER_H
|
f9d2e8a4c7e0268d784fbcf4798350b407136d1e | e9774443356c1a6aa99d68b6f2b9651fd591e5b2 | /sys/ExternalMechanism.cpp | 7ff79c4c800e6d335db507754abdd295ae676204 | [] | no_license | serik1987/vis-brain | abe971f0542620e94389f5bbf368b3f1e7bb3111 | f5524f624c9ca775c73013f43c9f553f231ac63f | refs/heads/master | 2020-06-18T19:46:08.533453 | 2019-12-15T01:37:34 | 2019-12-15T01:37:34 | 196,423,681 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,338 | cpp | ExternalMechanism.cpp | //
// Created by serik1987 on 14.11.2019.
//
#include "ExternalMechanism.h"
#include "../log/output.h"
namespace sys{
ExternalMechanism::ExternalMechanism(const std::string &filename) {
libraryHandle = dlopen(filename.c_str(), RTLD_LAZY);
if (libraryHandle == NULL){
mechanism_loading_error();
}
get_parameter_list = (int (*)(int*, const char***))loadFunction("get_parameter_list");
if (get_parameter_list(¶meter_number, ¶meter_names)){
throw get_parameters_name_list_error();
}
get_parameter_value = (int (*)(const char*, double*))loadFunction("get_parameter_value");
set_parameter_value = (int (*)(const char*, double))loadFunction("set_parameter_value");
initialize_buffers = (int (*)())loadFunction("initialize_buffers");
finalize_buffers = (int (*)())loadFunction("finalize_buffers");
}
ExternalMechanism::~ExternalMechanism() {
if (dlclose(libraryHandle)){
std::cerr << "ERROR DURING THE LIBRARY CLOSE\n";
}
}
void *ExternalMechanism::loadFunction(const std::string &name) {
void* result;
result = dlsym(libraryHandle, name.c_str());
if (result == NULL){
throw function_loading_error(name);
}
return result;
}
} |
b4172cfcc10ad116dbd0947e1d2184d86e57d77b | ac72a8a6f684f036e58d94ca7b00255759049baf | /source/gui/widgets/gui_image.h | 0a4737294c4906f71022e63dc43994d1868722c8 | [] | no_license | VBelles/MomentumEngine-Real | 27e988f3d46b19837e5f71fafe9a1591b2b85ce3 | a549158a1bbf1e1ca088a0f4bdd039ca17a3228d | refs/heads/master | 2023-08-04T14:11:17.000159 | 2018-11-15T16:48:33 | 2018-11-15T16:48:33 | 120,664,651 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 314 | h | gui_image.h | #pragma once
#include "gui/gui_widget.h"
namespace GUI {
class CImage : public CWidget {
public:
CImage() = default;
void render() override;
TImageParams* getImageParams() override;
private:
CTimer2 timer;
TImageParams _imageParams;
std::pair<VEC2, VEC2> getUV();
friend class CParser;
};
}
|
d53e17b50f601bc12099045d6de2543bb9ee37b9 | 8d8db4691575c52631a023f01c0007dfc91e4914 | /next_permu.cpp | 574cda58c0c193b4840f5130f89753f363a2b049 | [] | no_license | TheKillerAboy/BasicRevision | 5f56a0ccb0da5e64c5b806f71f0fd0f8d025d0ec | e5e573772caa47115ac9e8af994ecceb012c1540 | refs/heads/master | 2020-09-03T20:38:46.856767 | 2020-01-02T07:41:04 | 2020-01-02T07:41:04 | 219,564,318 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 674 | cpp | next_permu.cpp | #include <iostream>
using namespace std;
void swap(int* arr, int a, int b){
if(a==b){
return;
}
arr[a] = arr[a]^arr[b];
arr[b] = arr[a]^arr[b];
arr[a] = arr[a]^arr[b];
}
bool next_permu(int* arr, int n){
int l = n-1;
for(int i = n-2; i >= 0; i--){
if(arr[i] > arr[i+1]){
l--;
}
else{
break;
}
}
if(l==0){
return false;
}
int swa = -1;
for(int i = n-1; i >= l; i--){
if(arr[i] > arr[l-1]){
swa = i;
break;
}
}
swap(arr,l-1,swa);
for(int i = l; i <= (n-1+l)>>1; i++){
swap(arr,i,n-1+l-i);
}
return true;
}
int main(){
int arr[] = {3,2,1};
next_permu(arr,3);
for(int i = 0; i < 3; i++){
cout<<arr[i]<<' ';
}
return 0;
} |
b2f4bb3eff4a8ad3c13492b6a9658a25610f4dd4 | b78266f0d22f0183344d654194e2b1685f3ea15d | /bindings/CPP-CodeSynthesis/QIF_30/QIF_30/export.hxx | 03feeeed27c86466a1ae5d047c3f8b6150aee501 | [
"BSL-1.0"
] | permissive | xiazhongding/qif-community | 47a552c70515031bb8e29fffd8841f331c9c6442 | d1ee5fbe6c126ef7f25ab5f8653b35d7daa4c0b4 | refs/heads/master | 2023-09-02T07:58:12.974300 | 2021-11-12T19:52:03 | 2021-11-12T19:52:03 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 191 | hxx | export.hxx | #ifdef QIF_STATIC_LIBS
#define QIF30_SYMBOL_DECL
#else
#ifdef QIF30_EXPORTS
#define QIF30_SYMBOL_DECL __declspec(dllexport)
#else
#define QIF30_SYMBOL_DECL __declspec(dllimport)
#endif
#endif |
8ed02eb4a8b1aa5726431f95ffaa4afa9159195c | 7232d5ddc5484b6574ea63f283ef6d46ed368c93 | /tools/llvm-java/include/llvm/Java/Compiler.h | 2751de17958d3acde7a6feb084e554fdc3d5fefe | [
"NCSA"
] | permissive | JianpingZeng/llvm-java | 3c00e4bd58eec6b0eccda5707849c6493c749f05 | d89c66683b86616a0b7e8a92e1eb8e0a65b7646c | refs/heads/master | 2020-04-04T00:14:43.470390 | 2020-01-20T04:02:10 | 2020-01-20T04:02:10 | 155,645,875 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 785 | h | Compiler.h | //===-- Compiler.h - Java bytecode compiler ---------------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file was developed by the LLVM research group and is distributed under
// the University of Illinois Open Source License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file contains Java bytecode to LLVM bytecode compiler.
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_JAVA_COMPILER_H
#define LLVM_JAVA_COMPILER_H
#include <llvm/IR/Module.h>
#include <memory>
namespace llvm { namespace Java {
Module* compile(const std::string className);
} } // namespace llvm::Java
#endif//LLVM_JAVA_COMPILER_H
|
4e02620b7c7eb88f6f1f6f506445d2c234ea004b | 069d4d60ed3bded70ad32e8b19371c453efb6655 | /lua/runtime/lua_runtime.cc | 3035146955045bab7edf94e438dc1266523cb432 | [
"Apache-2.0"
] | permissive | openppl-public/ppl.nn | 5f3e4f0c1a10bd2ba267fdc27ff533fb9074f1ed | 99a2fdf6e4879862da5cac0167af5ea968eaf039 | refs/heads/master | 2023-08-17T07:31:50.494617 | 2023-08-16T11:24:54 | 2023-08-16T15:05:11 | 381,712,622 | 1,143 | 224 | Apache-2.0 | 2023-09-08T16:33:08 | 2021-06-30T13:32:17 | C++ | UTF-8 | C++ | false | false | 2,653 | cc | lua_runtime.cc | // Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you 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 "lua_runtime.h"
#include "lua_tensor.h"
#include "luacpp/luacpp.h"
using namespace std;
using namespace luacpp;
using namespace ppl::common;
namespace ppl { namespace nn { namespace lua {
void RegisterRuntime(const shared_ptr<LuaState>& lstate, const shared_ptr<LuaTable>& lmodule) {
auto tensor_class = lmodule->GetClass<LuaTensor>("Tensor");
auto lclass = lstate->CreateClass<LuaRuntime>()
.DefMember("GetInputCount", [](const LuaRuntime* lruntime) -> uint32_t {
return lruntime->ptr->GetInputCount();
})
.DefMember("GetInputTensor", [tensor_class, lstate](const LuaRuntime* lruntime, uint32_t idx) -> LuaObject {
auto tensor = lruntime->ptr->GetInputTensor(idx);
if (!tensor) {
return lstate->CreateNil();
}
return tensor_class.CreateInstance(tensor);
})
.DefMember("Run", [](LuaRuntime* lruntime) -> RetCode {
return lruntime->ptr->Run();
})
.DefMember("GetOutputCount", [](const LuaRuntime* lruntime) -> uint32_t {
return lruntime->ptr->GetOutputCount();
})
.DefMember("GetOutputTensor", [tensor_class, lstate](const LuaRuntime* lruntime, uint32_t idx) -> LuaObject {
auto tensor = lruntime->ptr->GetOutputTensor(idx);
if (!tensor) {
return lstate->CreateNil();
}
return tensor_class.CreateInstance(tensor);
})
.DefMember("GetTensor", [tensor_class, lstate](const LuaRuntime* lruntime, const char* name) -> LuaObject {
auto tensor = lruntime->ptr->GetTensor(name);
if (!tensor) {
return lstate->CreateNil();
}
return tensor_class.CreateInstance(tensor);
});
lmodule->Set("Runtime", lclass);
}
}}}
|
66f61cfda4721a70fd8bbed31135ce04228f88ef | dd898eda16dd87bec97dd00bf57fbb2667104f07 | /prim.cpp | 1cd3d0808b122544bb5b849f5ad577461c89f8cd | [] | no_license | sequix/mazer | 64b32b823179594e9564ae5028313987abb1f248 | de730d815aa374e30b67f79914e50e5cacd560c9 | refs/heads/master | 2021-01-12T06:07:45.603441 | 2016-12-31T02:51:02 | 2016-12-31T02:51:02 | 77,305,869 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,011 | cpp | prim.cpp | // Generate maze with Prim
#include <bits/stdc++.h>
using namespace std;
const int MAXN = 50; // maximum size of the maze MAXN * MAXN
const int reverse_dir[] = {2, 3, 0, 1};
struct P {
int u, v, d, w;
P(int u, int v, int d, int w): u(u), v(v), d(d), w(w) {}
bool operator<(const P &p) const { return w < p.w; }
};
struct Edge {
int v, d, w, next;
bool operator<(const Edge &e) const { return w < e.w; }
} eg[MAXN*MAXN*4];
int row, col;
int egc, head[MAXN*MAXN];
bool used[MAXN*MAXN];
bool M[MAXN][MAXN][4];
// add a edge <u, v> with weight w
void add(int u, int v, int d, int w)
{
eg[egc] = (Edge){v,d,w,head[u]};
head[u] = egc++;
}
// transfrom 1-d coodinate to 2-d coodinate
void u2p(int u, int &r, int &c)
{
r = u / col, c = u % col;
}
// generation of the maze
void generate()
{
int r, c, nr, nc;
priority_queue<P> que;
memset(head, -1, sizeof(head));
// initialize all the edges
for(int i = 0; i < row; ++i) {
for(int j = 0; j < col; ++j) {
if(j < col-1) add(i*col+j, i*col+(j+1), 1, rand());
if(i < row-1) add(i*col+j, (i+1)*col+j, 2, rand());
}
}
// prim
que.push(P(0, 0, 0, 0));
while(!que.empty()) {
P p = que.top(); que.pop();
if(used[p.v]) continue;
used[p.v] = true;
if(p.u != p.v) {
u2p(p.u, r, c);
u2p(p.v, nr, nc);
M[r][c][p.d] = 1;
M[nr][nc][reverse_dir[p.d]] = 1;
}
for(int pe = head[p.v]; pe != -1; pe = eg[pe].next)
que.push(P(p.v, eg[pe].v, eg[pe].d, eg[pe].w));
}
}
int main(int argc, char *argv[])
{
if(argc != 3) {
fprintf(stderr, "usage: %s ROW COL\n", argv[0]);
exit(1);
}
srand(time(0));
row = atoi(argv[1]);
col = atoi(argv[2]);
generate();
for(int i = 0; i < row; ++i)
for(int j = 0; j < col; ++j)
for(int k = 0; k < 4; ++k)
printf("%d\n", M[i][j][k]);
return 0;
}
|
6d549de9a874bba725dc6efc84eb7a0c948d267b | 9ab11e1e76fb7654ba1e247d035da873f4256d6a | /Sources/RainbowEngine/UI/src/UI/Widgets/InputFields/InputInt.cpp | f9e51c656122418b8724c18f4e48c5721a483e39 | [] | no_license | Tekh-ops/RainbowEngine | f7e565ddcbdcab0e8fb663d8e51988b73895698f | 5d1dc91d15fc988d7eacdd23900d0d5c398d5f1b | refs/heads/master | 2023-04-03T13:55:10.200479 | 2021-04-01T15:14:48 | 2021-04-01T15:14:48 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 365 | cpp | InputInt.cpp |
#include "UI/Widgets/InputFields/InputInt.h"
UI::Widgets::InputFields::InputInt::InputInt(int p_defaultValue, int p_step, int p_fastStep, const std::string & p_label, const std::string & p_format, bool p_selectAllOnClick)
: InputSingleScalar<int>(ImGuiDataType_::ImGuiDataType_S32, p_defaultValue, p_step, p_fastStep, p_label, p_format, p_selectAllOnClick)
{
}
|
9657a7988ef14de89667fc6861b1803bf4b51a8f | 22212b6400346c5ec3f5927703ad912566d3474f | /src/Kernel/VectorString.h | 4b3b6c094c8f781767c53b0f944c0a1d0b72fc80 | [
"LicenseRef-scancode-unknown-license-reference",
"MIT"
] | permissive | irov/Mengine | 673a9f35ab10ac93d42301bc34514a852c0f150d | 8118e4a4a066ffba82bda1f668c1e7a528b6b717 | refs/heads/master | 2023-09-04T03:19:23.686213 | 2023-09-03T16:05:24 | 2023-09-03T16:05:24 | 41,422,567 | 46 | 17 | MIT | 2022-09-26T18:41:33 | 2015-08-26T11:44:35 | C++ | UTF-8 | C++ | false | false | 226 | h | VectorString.h | #pragma once
#include "Kernel/Vector.h"
#include "Kernel/String.h"
namespace Mengine
{
typedef Vector<String> VectorString;
typedef Vector<WString> VectorWString;
typedef Vector<U32String> VectorU32String;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.